Entity Framework-using transactions or savechanges (false) and acceptallchanges ()?

Source: Internet
Author: User

Link

With the Entity Framework most of the timeSavechanges ()Is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.

Sometimes thoughSavechanges (false) + acceptallchanges ()Pairing is useful.

The most useful place for this is in situations where you want to do a Distributed Transaction Processing SS two different contexts.

I. e. Something like this (bad ):

Using (transactionscope scope = new transactionscope () {// do something with context1 // do something with context2 // save and discard changes context1.savechanges (); // save and discard changes context2.savechanges (); // if we get here things are looking good. scope. complete ();}

IfContext1.savechanges ()SucceedsContext2.savechanges ()Fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes onContext1, So you can't replay or wait tively log the failure.

But if you change your code to look like this:

Using (transactionscope scope = new transactionscope () {// do something with context1 // do something with context2 // save changes but don't discard yet context1.savechanges (false ); // save changes but don't discard yet context2.savechanges (false); // if we get here things are looking good. scope. complete (); context1.acceptallchanges (); context2.acceptallchanges ();}

While the callSavechanges (false)Sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogateObjectstatemanagerIf you want.

This means if the transaction actually aborts you can compensate, by either re-trying or logging state of each contextsObjectstatemanagerSomewhere.

See my blog post for more.

Entity Framework-using transactions or savechanges (false) and acceptallchanges ()?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.