Multiple SaveChanges calls in entity framework

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


It is a bad practice to call SaveChanges multiple times (Without a transaction scope) when the related entities should be persisted in a single transaction. What you have created is a leaky abstraction. Create a separate Unit of Work class or use the ObjectContext/DbContext itself.


I would strongly advise against calling SaveChanges() in each method. Using the repository pattern and unit of work is the better way forward. Unit of work, allows you to be more efficient with your db calls and also helps you against polluting your db if some data is not valid (e.g. user details is ok, but address fails).

Here's a good tutorial to help you.

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application