Connection.BeginTransaction and Entity Framework 4?

岁酱吖の 提交于 2020-01-16 19:23:06

问题


I am trying to use transactions with EF4 Code-first with an unit of work implementation. Is there a reason we cannot use Connection.BeginTransaction from the context ? It is only intended to be used in SQL transactions only ? Because when im calling it i get the error : Illegal operation. Connection is closed.

Thanks.


回答1:


Part of the answer will be that DbContext.SaveChanges() is automatically transactional, so in many cases, you will not need to roll your own transactions. What is your scenario, and why do you think that you need to manually do transactions?

If you decide you need them, wrap SaveChanges in a transaction:

    using (TransactionScope transaction = new TransactionScope())
    {
        context.SaveChanges();
    }

If you run Profiler, you will note that the transaction is rolled back once you leave the using{} block. To commit your transaction, call transaction.Complete(); after SaveChanges().



来源:https://stackoverflow.com/questions/4939405/connection-begintransaction-and-entity-framework-4

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