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?
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
)