Reputation: 943
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?
Upvotes: 0
Views: 929
Reputation: 1
I actually think:
var product = new Product { Id = productId };
if(product == null)
throw new ItemNotFound($"Need custom error handler");
db.Entry(product).State = System.Data.Entity.EntityState.Deleted;
db.SaveChangesAsync();
P.S. my version:
public async Task DeleteTemplate(int id)
{
var entity = await RepositoryContext.Set<Product>().FindAsync(id);
if(entity == null) throw new ItemNotFoundException($"we don't have it in the db. We have nothing to remove");
RepositoryContext.Product.Remove(entity);
await RepositoryContext.SaveChangesAsync();
}
In a real project it is better to use repositoryContext.
Upvotes: 0
Reputation: 3355
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.
Upvotes: 2