Reputation: 869
I need to update more than one update statements, but all should work on automicity i.e update all or none.
on internet and in someother SO Questions i have found how to use Transaction but i didnt' find any of them saying to update mulitple statements in one transaction. See below three updates statements, currently there not running under transaction
/// this are my update calls.
var report = reportRepository.Update(reportModel);
var book = bookRepository.Update(bookModel);
var mobile = mobileRepository.Update(mobileModel);
// each Update method for all repository will looks like
public returnModel Update(someModel model)
{
// assign values from model to entity
Context.ObjectStateManager.ChangeObjectState(entity,System.Data.EntityState.Modified)
Context.SaveChanges();
}
Upvotes: 2
Views: 2721
Reputation: 30152
As Darin mentioned use a transaction scope or my preferred method is to have your repositories belong to an IUnitOfWork interface. Calling update simply sets the state to modified and the SaveChanges happens OUTSIDE of your repository to save all changes at once. This should happen automatically inside of one transaction.
So you call all your Updates and then unitOfWork.SaveChanges where your custom unit of work class contains a reference to your context and implements a method defines in IUnitOfWork called Save()
Upvotes: 1
Reputation: 5987
Basically you need to manage it through TransactionScope Class and using this you can set up multiple update to a Model and then use Transaction.Complete to save your stuff in one transaction.
Please check Updating multiple objects in single transaction in entity framework for more details.
Upvotes: 0
Reputation: 1038840
You could wrap the updates in a TransactionScope:
using (TransactionScope transaction = new TransactionScope())
{
var report = reportRepository.Update(reportModel);
var book = bookRepository.Update(bookModel);
var mobile = mobileRepository.Update(mobileModel);
...
transaction.Complete();
}
Upvotes: 4