Doing transactions with Entity Framework Code First

左心房为你撑大大i 提交于 2019-12-10 16:45:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!