Search code examples
c#entity-frameworkrepository-pattern

Delete needs to Read first in Repository Pattern?


I have seen good sources about Repository Pattern like the video Repository Pattern with C# and Entity Framework, Done Right and Aspnet Boilerplate. I know that the repository should not have logic to commit data, which is responsibility of the Unit of Work. But seems to me a little of overweight doing delete of parent record with children, because you may need to read the parent, all of its children, to then delete. You can see example of implementation like that, using Entity Framework in the same video, deleting authors and course. The Aspnet Boilerplate has a implementation to delete with a primary key, which read the entity before deleting too. So, I ask: can I use a delete commands and still respect the pattern? Is there any good example out there?


Solution

  • I can't see how this might be an issue if you inject one Context per request or rather one Unit of work in this case, since it's the same context all across the current request, you can simply delete the parent and set cascade for its children, something like:

    var product = new Product { Id = productId };
    db.Entry(product).State = System.Data.Entity.EntityState.Deleted;
    db.SaveChanges();
    

    This way you do one less read, on top of that take a look at components like MediatR, and why you don't even need a repository if you use an ORM.