I’m in a discussion with another developer about whether or not to have a repo.SaveChanges() method exposed in our Entity Framework 5 repository.
We’re considering having a repo that automatically saves changes like this (quick and dirty example):
public class Repo {
private OurEfContext _context = new OurEfContext();
public void PersistCustomer(Customer cust)
{
// update customer code here
_context.SaveChanges(); // <-- is this okay?
}
}
The other option we’re considering is to expose a separate Repo.PersistChanges() method like this:
public class Repo {
private OurEfContext _context = new OurEfContext();
public void PersistCustomer(Customer cust)
{
// update customer code here
// no call to _context.SaveChanges();
}
public void PersistChanges()
{
_context.SaveChanges();
}
}
Most examples that I have seen use the second pattern. Is one pattern more ‘correct’ than the other?
Saving after every change prevents you from saving batches of entities. In certain graph structures this can be a correctness problem, in other cases it just drives the CPU load up. The cost of
SaveChangesis not just the writing, but also traversing entities loaded into the context.Why work against Entity Framework? Do, what it wants you to do: Save batches and call
SaveChangesat the end when all changes to entities have been made.The method
PersistCustomeris wrongly named: It persists everything, not just the customer. You cannot persist a single entity with EF. Your abstraction (the repository) is broken.People often wrap EF in a generic repository that adds no functionality but removes functionality. That has never made sense to me.