Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Entity Framework handle transactions?

Does Entity Framework use a transaction for when you call SaveChanges on your context? Is there any way to turn off transactions completely, or have a certain entity opt out of a transaction?

AdventureWorksEntities db = new AdventureWorksEntities();

Product p1 = new Product();
// ...

Product p2 = new Product();
// set invalid data

db.Products.AddObject(p1);
db.Products.AddObject(p2);

// what happens when I call this - does it roll back everything?
// can i tell p2 not to participate in the transaction?
db.SaveChanges();
like image 439
Dismissile Avatar asked Feb 24 '11 22:02

Dismissile


People also ask

Why you shouldn't use Entity Framework with transactions?

No process will be able to access the tables you have touched (even reading from it) during your transaction. That can lead to Deadlocks pretty fast and you want to avoid them at all costs!

Does EF core use transaction?

EF Core relies on database providers to implement support for System. Transactions. If a provider does not implement support for System.

How do I start a transaction in Entity Framework?

Starting with EF6 the framework now provides: Database. BeginTransaction() : An easier method for a user to start and complete transactions themselves within an existing DbContext – allowing several operations to be combined within the same transaction and hence either all committed or all rolled back as one.

How does Entity Framework works internally?

The Entity Framework uses information in the model and mapping files to translate object queries against entity types represented in the conceptual model into data source-specific queries. Query results are materialized into objects that the Entity Framework manages.


1 Answers

Yes, EF4 will create a new transaction if one does not already exist. See

http://msdn.microsoft.com/en-us/library/bb896325.aspx

When you call SaveChanges, if a current transaction exists, the Entity Framework uses this transaction for operations against the data source. Otherwise, it creates a new transaction for the operation. You can define transactions by using EntityTransaction, Transaction, or TransactionScope.

No, there is no way to exempt a single entity from the transaction.

Not sure about your third question - about whether you can turn off transactions completely, but I'm guessing not based on the above excerpt.

I know this isn't the answer you wanted to hear, but if you want P2 to save regardless of whether P1 succeeds, you would need to save P2 into a different object context.

like image 166
Adam Rackis Avatar answered Oct 09 '22 19:10

Adam Rackis