简体   繁体   中英

Native Entity Framework Transactions Behavior

I read some articles, like this one, where they say:

In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes. When you execute another such operation a new transaction is started.

But I can't understand from this description how does EF behaves when I have multiple changes to be executed. Does it wrap all the insert , update or delete into one transaction , or each one of them get it's own transaction ? The term " that operation " in the text can be both the whole SaveChanges() operation or the individual insert , update or delete .

A practical example of my question is:

using(var context = new MyContext())
{
    context.MyClass1.Add(myObject1);
    var myObject2 = context.MyClass2.Single();
    myObject2.Value1 = 10;

    context.SaveChanges();
}

I would like that if there are any errors setting myObject2.Value1 to 10 , the whole operation is canceled, so myObject1 isn't added to the DB as well and vice versa.

Does it wrap all the insert, update or delete into one transaction, or each one of them get it's own transaction?

For the time you instantiate your context until you reach the SaveChanges() method, all operations insert, update and update are executed in a single transaction hence as an atomic operation to the database server. If one of your operation failed all of the operations that are executed in success before reaching the failed one are rollback. But your entites will still have their modifications you have done on them. Only the database server will reject the changes.

The term "that operation" in the text can be both the whole SaveChanges() operation or the individual insert, update or delete.

It represents the hole SaveChanges as an ACID (Atomicity, Consistency, Isolation, Durability) operation.

I would like that if there are any errors setting myObject2.Value1 to 10, the whole operation is canceled, so myObject1 isn't added to the DB as well and vice versa.

Your object modifications aren't added to the database but object's state in your application is not lost. The value 10 will still be there as a value of Value1 if you check the value of this property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM