How to use transactions with the Entity Framework?

前端 未结 5 510
说谎
说谎 2020-12-13 13:47

When you have code like this:

Something something = new Something();
BlahEntities b = new BlahEntities()    
b.AddToSomethingSet(something);
b.SaveChanges();         


        
5条回答
  •  没有蜡笔的小新
    2020-12-13 14:22

    I know that for LINQ to SQL, the data context will create a transaction for SubmitChanges() if there is no existing ambient transaction (TransactionScope is an "ambient" transaction). I haven't seen this documented for LINQ to Entities, but I have seen behavior to suggest that it's true for Entity Framework as well.

    So as long as you use one SubmitChanges() (L2SQL) or SaveChanges() (Linq to Entities) for all the related changes, you should be OK without using TransactionScope. You need a TransactionScope when

    1. Saving multiple changes with multiple SubmitChanges/SaveChanges for one transaction.
    2. Updating multiple data sources within one transaction (e.g., Linq and ASP.NET membership SQL provider).
    3. Calling other methods that may do their own updates.

    I've had trouble with nested TransactionScopes. They're supposed to work, and simple test cases work, but when I get into production code, the "inner" transaction seems to be the same object as the outer transaction. Symptoms include errors that are either "transaction committed, you can't use this transaction any more" or "this transaction object has already been disposed". The errors occur in the outer transaction after the inner transaction has done its work.

提交回复
热议问题