【发布时间】:2020-03-05 17:09:03
【问题描述】:
我有 .net core rest api,它包含混合结构,其中只包含存储库而不包含服务层。
现在,我在基本存储库和主要结构方面面临一个问题。让我先解释一下这个问题。
所以,考虑一个实体。假设 Product 和下面是该实体的定义。该实体有一个名为 FullAuditedEntity 的基类。
[Table(name: "Products")]
public class Product : FullAuditedEntity
{
public string Name { get; set; }
}
public class FullAuditedEntity: IFullAuditedEntity
{
public FullAuditedEntity() { }
[Key]
public virtual int Id { get; set; }
}
public interface IFullAuditedEntity
{
int Id { get; set; }
}
基础库及其接口如下。
public class EntityBaseRepository<T> : IEntityBaseRepository<T> where T : class, IFullAuditedEntity, new()
{
private readonly ApplicationContext context;
public EntityBaseRepository(ApplicationContext context)
{
this.context = context;
}
public virtual IEnumerable<T> items => context.Set<T>().AsEnumerable().OrderByDescending(m => m.Id);
public virtual T GetSingle(int id) => context.Set<T>().FirstOrDefault(x => x.Id == id);
}
public interface IEntityBaseRepository<T> where T : class, new()
{
IEnumerable<T> items { get; }
T GetSingle(int id);
}
所以,我的产品存储库将是这样的。
public interface IProductRepository : IEntityBaseRepository<Product> { }
public class ProductRepository : EntityBaseRepository<Product>, IProductRepository
{
private readonly ApplicationContext context;
public ProductRepository(ApplicationContext context) : base(context: context)
{
this.context = context;
}
}
现在,到目前为止一切都很好,我可以在控制器中访问这个存储库,并且可以执行基类中列出的操作。
我面临的问题:因此,对于这种结构,如果我尝试添加任何没有 FullAuditedEntity 的新实体(请参阅上面的产品实体,我在那里有基类完整的审计实体),我的结构存储库失败并给出错误。
假设我尝试添加新实体实现,并且这个新实体有一个随机 Id,所以我不想继承 FullAuditedEnitity 基类。现在在这种情况下,大多数事情都可以正常工作,但是当我尝试为实现实体创建存储库时,它会给出一般错误。请参阅下面的快照。
到目前为止我尝试了什么......
我正在考虑创建一个并行 Base 存储库,它不会将 FullAuditedEntity 作为泛型类继承,但我不确定这是否是最佳实践。我还担心如果我在当前的存储库模式和依赖注入结构中犯了任何错误怎么办?
任何帮助世界都是最好的,真的很感激。
提前感谢您抽出宝贵时间。
【问题讨论】:
标签: c# dependency-injection repository-pattern asp.net-core-2.1 ef-core-2.1