【发布时间】:2017-11-19 09:09:27
【问题描述】:
我正在使用 ASP.NET MVC 和 Onion Architecture 创建一个 Intranet 网站。我一直在实施存储库模式,但我遇到了困难。
假设我有一个包含 IDDocument 的 Document 表。然后这是我的回购(只有一种方法):
class Repository<T> : IRepository<T> where T : class
{
private readonly PrincipalServerContext context;
private DbSet<T> entities;
//Constructor and stuff here
public T Get(long id)
{
return entities.SingleOrDefault(s => s.IDDocument == id);//Here is my problem
}
}
问题是我不能使用它,因为 T 未被识别为来自 Document 表。解决方案是创建一个 BaseEntity:
public class BaseEntity{
public int ID{get;set;}
}
然后我的文档 POCO 变成:
public class Document : BaseEntity{
//Properties here
}
还有我的回购:
class Repository<T> : IRepository<T> where T : BaseEntity
{
private readonly PrincipalServerContext context;
private DbSet<T> entities;
public T Get(long id)
{
return entities.SingleOrDefault(s => s.ID == id);//Here is my problem
}
}
但是我不想理想地这样做。我在通用存储库中喜欢的是它允许我不对所有不同的表重复相同的代码(我有 300 多个表)。但是拥有一个 BaseEntity 也意味着重组我已经完成的很多工作。 是否有可能拥有一个可以在没有此 BaseEntity 类的任何 POCO 上应用的通用存储库?
感谢您的帮助
【问题讨论】:
-
你至少需要一个接口来给编译器一些关于
<T>的信息 -
当您的泛型类采用
T : class时,您如何期望您的代码知道ID是什么? -
@DanielA.White 好的,谢谢
-
@maccettura 这就是我的问题的重点......
-
@Flexabustbergson 使用必须具有特定形状(即具有 ID)的泛型时,您需要提供通用类型。无论是接口、抽象类,还是其他类继承自的常规类。在某些时候,您需要找出所有类之间的共性,如果没有,那么您不应该使用泛型来尝试强制它们都相同(当然,除非您不需要访问任何泛型类中的成员/属性,那么它们实际上是什么形状并不重要)。
标签: c# repository-pattern onion-architecture