具有接口(interface)的 C# MVC 通用存储库类

标签 c# asp.net-mvc generics inheritance repository

我怎样才能实现类似下面的例子?

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/

相关文章:

java - 创建泛型集合数组

c# - 尝试将我的 Web 应用程序从 VS Community 2015 发布到 Azure 时出错。错误: Can't find existing loaded project:http://localhost:55809

c# - Observable.Zip 当要压缩的序列数在运行时未知时

c# - 如何在 C# 中生成随机深色?

asp.net-mvc - ASP.NET MVC 和 Web API 模型绑定(bind) - 如何绑定(bind)到名称不允许的属性?

c# - 我在哪里可以找到 System.Linq.Dynamic dll?

c# - 发送电子邮件 MVC 时出错

c# - 显示用于更改 ViewModel 状态的交替图像

c# - 创建通用类 C#

c# - 使用别名时无法隐式转换类型错误