删除需要在存储库模式中先读取?

Delete needs to Read first in Repository Pattern?

我看过关于存储库模式的好资料,例如视频 Repository Pattern with C# and Entity Framework, Done Right 和 Aspnet Boilerplate。我知道存储库不应该有提交数据的逻辑,这是工作单元的责任。 但在我看来,删除带有子项的父记录有点过分,因为您可能需要读取父项及其所有子项,然后才能删除。您可以看到类似的实施示例,在同一视频中使用 Entity Framework,deleting authors and course. The Aspnet Boilerplate has a implementation to delete with a primary key, which read the entity before deleting too。 所以,我问:我可以使用删除命令并仍然遵守模式吗?有什么好的例子吗?

如果您为每个请求注入一个上下文或者在这种情况下更确切地说是一个工作单元,我看不出这可能是个问题,因为它在当前请求中都是相同的上下文,您可以简单地删除父级并为其子级设置级联,例如:

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

这样你就少了一次阅读,如果你使用 ORM,那么再看看像 MediatR, and why you don't even need a repository 这样的组件。

其实我觉得:

var product = new Product { Id = productId }; // what if here you have null?? (I didn't see any checking) in the next row will be exception
if(product == null) 
    throw new ItemNotFound($"thi is custom error handler or do magic")

db.Entry(product).State = System.Data.Entity.EntityState.Deleted;
db.SaveChanges(); // better in repository layer to have async method like await 
db.SaveChangesAsync();

P.S。我的版本:

public 异步任务 DeleteTemplate(int id) { var entity = await RepositoryContext.Set().FindAsync(id); if(entity == null) throw new ItemNotFoundException($"我们在 db.have 中没有它,没有什么可删除的"); RepositoryContext.Product.Remove(实体);

        await RepositoryContext.SaveChangesAsync();
    }

在实际项目中最好使用 repositoryContect。