ISqlModelMapper.SaveChangesAsync() Method
.NET Standard 2.x
Asynchronously saves all of the data changes to the database, by executing the database table operations tracked by the ISqlModelMapper
object, and calls the tracked Action
delegates during operations.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public Task<IDbResult> SaveChangesAsync()
Returns
Task<IDbResult>
Returns a task that represents the asynchronous operation.
Remarks
When the database is updated successfully, SqlModelMapper is restored to its initial state which will not track data changes.
To continue using SqlModelMapper for other data operations, use ISqlModelMapper.TrackCreate method etc. to track the changes again.
Database Transaction
This method will create by default a database transaction where all of the SQL DML will be executed.
When any exceptions occur, the database transaction will be automatically rolled back.
Validation
Before updating the database, the system will validate the data in the model. If detects any error, exceptions will be thrown.
Examples
The following code example demonstrates how to register two new students.
using System;
using System.Threading;
using System.Threading.Tasks;
using Appeon.ApiDoc.Models.School;
using SnapObjects.Data;
namespace Appeon.ApiDoc.ISqlModelMapperExamples
{
public class SaveChangesAsyncExample
{
private readonly SchoolContext _context;
public SaveChangesAsyncExample(SchoolContext dataContext)
{
// Sets the data context.
_context = dataContext;
}
public async Task<int> Example1()
{
var mapper = _context.SqlModelMapper;
// Tracks the two new students and saves changes to the database asynchronously.
var personA = new Person()
{
LastName = "Senior",
FirstName = "Letitia",
EnrollmentDate = DateTime.Now,
Discriminator = "Student"
};
var personB = new Person()
{
LastName = "Ward",
FirstName = "Lilith",
EnrollmentDate = DateTime.Now,
Discriminator = "Student"
};
var dbResult = await mapper.TrackCreate(personA)
.TrackCreate(personB)
.SaveChangesAsync();
Console.WriteLine("{0} records have been inserted into the database.",
dbResult.InsertedCount);
return dbResult.AffectedCount;
/* The code produces the following output:
2 records have been inserted into the database.
*/
}
}
}
Applies to
.NET Standard
2.x