我怎样才能实现类似下面的例子?
public interface IGenericRepository {
int id { get; }
T GetById<T>() where T : class
}
public class GenericRepository : IGenericRepository {
//Some code here
public T GetById<T>(int tid) where T : class
{
return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
}
}
我想按如下方式使用它:
GenericRepository gr = new GenericRepository();
Category cat = gr.GetById<Category>(15);
当然这段代码不起作用,因为如果我定义 T : class
然后是 tbl.id
部分将不起作用。但当然,应该有办法实现这一点。
更新
考虑到 driis 的回答,我正在执行以下操作,但我仍然无法正常工作:
public interface IEntity
{
int id { get; }
}
public interface IGenericRepository : IEntity
{
T GetById<T>(int id);
}
public class GenericRepository : IGenericRepository
{
public T GetById<T>(int id) {
return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
}
}
此时tbl.id
有效,但是 dataContext.GetTable<T>
给我一个错误。
最佳答案
您可以约束 T 为包含 ID 的类型,您可能需要它的接口(interface):
public interface IEntity
{
int Id { get; }
}
然后将您的泛型方法声明为:
public IQueryable<T> GetById<T>(int tid) where T : IEntity
{
return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
}
当然,您需要为所有实体实现 IEntity。我猜您正在使用 Linq2Sql 或类似软件,在这种情况下,您可以只创建一个包含接口(interface)实现的部分类定义。
关于具有接口(interface)的 C# MVC 通用存储库类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6739827/