Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why include a Repo.SaveChanges() method in a repository?

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?

like image 903
quakkels Avatar asked Dec 20 '22 11:12

quakkels


2 Answers

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 SaveChanges is 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 SaveChanges at the end when all changes to entities have been made.

The method PersistCustomer is 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.

like image 68
usr Avatar answered Dec 23 '22 00:12

usr


I tend to support the second method.

The first one might "hide" the saving action and will look nicer to the user, but don't forget that you are losing control of the saving action. If you find yourself updating multiple entities, this will cause an overhead of multiple separated changes instead of having them executing at once - which means more execution time.

Eventhough it might feel like calling the "SaveChanges" redundantly, the second method will allow you to save multiple changes at once = no overhead.

I find limiting yourself by removing the ability to improve the performance as a needless act.

like image 20
Aviran Cohen Avatar answered Dec 23 '22 00:12

Aviran Cohen