Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mizrael
Created September 3, 2019 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mizrael/987d3b72ace169c3f34ab9c9072c1f21 to your computer and use it in GitHub Desktop.
Save mizrael/987d3b72ace169c3f34ab9c9072c1f21 to your computer and use it in GitHub Desktop.
using (var tran = await _dbContext.BeginTransactionAsync())
{
try
{
var modelsToRemove = await _dbContext.QueryModels
.Where(f => /* some filter here */)
.ToArrayAsync();
if (modelsToRemove.Any())
_dbContext.QueryModels.RemoveRange(modelsToRemove);
// remenber to call SaveChangesAsync() after every write in order to
// ensure that the operation has been performed.
// The Ef DbContext is not thread safe and if there are multiple instances of the
// service, data might not be persisted correctly.
await _dbContext.SaveChangesAsync();
if (newModels?.Any())
_dbContext.QueryModels.AddRange(newModels);
await _dbContext.SaveChangesAsync();
tran.Commit();
}
catch (Exception ex)
{
tran.Rollback();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment