Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple SaveChanges calls in entity framework

I am building my own custom repository, based on entity framework, and I'm creating some extension methods that allow me to save partial view models as entity models so I'm building my own Add and Update methods.

Currently, each method has SaveChanges() from DbContext called at the end which means for every model, one call will be invoked.

I'm building this base DAL pattern for MVC4 sites which means most of the time I will access 1 model, but it does not have to be the case though.

Is it too bad practice to call SaveChanges() for each model when updating i.e. 3 entities or should I add everything first to object context and than do SaveChanges() as some sort of transaction commit?

like image 203
Admir Tuzović Avatar asked Oct 26 '12 07:10

Admir Tuzović


People also ask

What's the point of multiple SaveChanges inside an Entity Framework core transaction?

In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.

How do I use SaveChanges in Entity Framework?

When SaveChanges() is executed to insert, update or delete on the database then Entity framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes.

When would you use SaveChanges false AcceptAllChanges ()?

Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful. The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts. If context1. SaveChanges() succeeds but context2.


Video Answer


1 Answers

I know it's kind of late answer but i found it useful to share.

Now in EF6 it's easier to achieve this by using dbContext.Database.BeginTransaction()

like this :

using (var context = new BloggingContext()) {     using (var dbContextTransaction = context.Database.BeginTransaction())     {         try         {             // do your changes             context.SaveChanges();              // do another changes             context.SaveChanges();              dbContextTransaction.Commit();         }         catch (Exception ex)         {             //Log, handle or absorbe I don't care ^_^         }     } } 

for more information look at this

again it's in EF6 Onwards

like image 74
Wahid Bitar Avatar answered Sep 21 '22 22:09

Wahid Bitar