我正在尝试为我目前正在开发的基于实体框架的项目编写一个通用的最适合大多数存储库模式的模板类。在(重简化)接口是:EntityFramework存储库模板 - 如何在模板类中编写GetByID lambda?
internal interface IRepository<T> where T : class
{
T GetByID(int id);
IEnumerable<T> GetAll();
IEnumerable<T> Query(Func<T, bool> filter);
}
GetByID被证明是杀手。在执行中:
public class Repository<T> : IRepository<T>,IUnitOfWork<T> where T : class
{
// etc...
public T GetByID(int id)
{
return this.ObjectSet.Single<T>(t=>t.ID == id);
}
t => t.ID == id是我努力的特定位。是否有可能在没有类特定信息可用的模板类中编写像那样的lambda函数?
虽然我可以做类似||的事情public T GetSingle( filter)||如果可能的话,我真的更喜欢更简单的GetByID,因为每个存储库绑定的类将作为一个坚实的规则拥有一个ID属性。 –
nathanchere
2010-05-31 06:47:05
到目前为止最接近的解决方案是返回查询(函数(x)CType(x,Object).ID = ID)其中查询是datacontext.Where(过滤器)的包装。 – nathanchere 2010-06-02 03:49:54