问题
There is an answer here to explain how to do transactions with Entity Framework However the solution does not work with code first. I have experimented and my tests indicate the following does work
using (var scope = new TransactionScope())
{
DBContext1.SaveChanges()
If (ForceFailure) return 0 // used in testing
DBContext2.SaveChanges()
scope.Complete();
}
However I feel nervous because I am no longer passing parameters to SaveChanges or calling AcceptAllChanges
How do I establish whether I can trust my solution?
回答1:
SaveChanges(Boolean)
is part of ObjectContext
, not DbContext
. Note that the method SaveChanges(Boolean)
in ObjectContext
is deprecated in favor of SaveChanges(SaveOptions).
If you still want to use DbContext
, you may be able to overload its own SaveChanges
method to use IObjectContextAdapter.ObjectContext, by using an extension method for example.
来源:https://stackoverflow.com/questions/14944802/doing-transactions-with-entity-framework-code-first