【发布时间】:2014-06-04 19:40:00
【问题描述】:
我已经在我的 ASP.NET Web API 项目中实现了存储库模式和工作单元。
效果很好。现在向我提出了一个关于存储库的问题,该存储库可以处理我的应用程序中有关设置目录的所有信息。
现在我必须在我的工作单元中创建所有引用 EF 实体的公共存储库,如下所示:
public IRepository<Document> Document { get { return GetStandardRepo<Document>(); } }
Document 是一个 EF 实体。 IRepository 实现了以下方法:
public interface IRepository<T> where T : class
{
IQueryable<T> GetAll();
IQueryable<T> GetAllReadOnly();
T GetById(int id);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(int id);
}
我的数据库中有大约 20 个用于安装目录的表,所以如果我遵循这种模式,我将不得不创建 20 个:
public IRepository<SetupEmployeeType> Document { get { return GetStandardRepo<SetupEmployeeType>(); } }
public IRepository<SetupMaritalStatus> Document { get { return GetStandardRepo<SetupMaritalStatus>(); } }
public IRepository<SetupRelationshipCode> Document { get { return GetStandardRepo<SetupRelationshipCode>(); } }
public IRepository<SetupLocationType> Document { get { return GetStandardRepo<SetupLocationType>(); } }
.....
.....
我正在考虑的一个解决方案是创建我自己的自定义 IRepository 实现,可能是 IATAlogRepository,如下所示:
public class CatalogRepository : EFRepository<EF Entity>, ICatalogRepository
{
public CatalogRepository (DbContext context) : base(context) { }
public IEnumerable<SetupEmployeeType> GetEmployeeTypes()
{
var catalog = DbContext
.Set<SetupEmployeeType>()
.ToList();
return catalog;
}
public IEnumerable<SetupMaritalStatus> GetMaritalStatus()
{
var catalog = DbContext
.Set<SetupMaritalStatus>()
.ToList();
return catalog;
}
}
我的问题是 CatalogRepository 必须继承自 EFRepository 但 T 不仅仅是一个实体,因为我会从不同的方法返回不同的实体.
这是正确的做法吗?
【问题讨论】:
标签: entity-framework entity-framework-4 repository-pattern unit-of-work