How expensive is Entity Framework SaveChanges? Auto-Save vs. explicit [context.SaveChanges on Dispose]

c# entity-framework entity-framework-core

Question

One question I have been wondering is, should I call context.SaveChanges() explicitly or let it be under Dispose().

Approach 1: Auto-Save

    public virtual void Dispose()
    {
        context.SaveChanges();
        context.Dispose();
    }

Let's say we add user into UserRepository (or using dependency injection)

  using (var repo = new UserRepository())
  {
       repo.Add(user);
  }

Approach 2: explicit save

    public virtual void SaveChanges()
    {
        context.SaveChanges();
    }

    public virtual void Dispose()
    {
        context.Dispose();
    }

Let's say we add user into UserRepository (or using dependency injection)

  using (var repo = new UserRepository())
  {
       repo.Add(user);
       repo.SaveChanges();
  }

So the question I have is: the Auto-Save produces cleaner code, but how expensive is the operation? Which is the better approach?

1
2
7/23/2017 8:28:57 PM

Accepted Answer

I don't know the details, but I doubt you want to be calling SaveChanges when performing a read only query, for example, and what you've shown would call SaveChanges in all cases.

I do write something similar, so that I can make a quick and easy write to the database, but you shouldn't mingle SaveChanges into the Dispose method itself, that's definitely bad.

public static void UseAndSave(
   Action<Context> pAction
) {
   using (var context = new Context()) {
      pAction(context);
      context.SaveChanges();
   }
}

...

Context.UseAndSave(context => context.Users.Add(user));

(Can also write a version that takes a Func)

0
7/23/2017 9:22:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow