Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 带接口的C MVC通用存储库类_C#_Asp.net Mvc_Generics_Inheritance_Repository - Fatal编程技术网

C# 带接口的C MVC通用存储库类

C# 带接口的C MVC通用存储库类,c#,asp.net-mvc,generics,inheritance,repository,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 {

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

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;
   }
}
此时tbl.id起作用,但dataContext.GetTable给了我一个错误。

您可以将T约束为包含id的类型,您可能需要它的接口:

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或类似的工具,在这种情况下,您可以创建一个包含接口实现的部分类定义。

您可以将T约束为包含ID的类型,您可能需要它的接口:

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或类似的工具,在这种情况下,您可以创建一个包含接口实现的部分类定义。

我应该在哪个接口中定义T getByidit tid?甚至还有一个更好的问题:我需要在接口中定义它吗DYou可能希望GetById出现在您的基本存储库界面中。很抱歉,我对这方面非常陌生,您能提供一个完整的示例吗?因为当我尝试实现IEntity时,GetTable不起作用,因为它需要引用类型。IEntity不应该有GetTable方法。它应该在IGenericRepository中,并按照您的模型在GenericRepository中实现。记住要注意通用约束where:part,它在接口和实现中需要相同。请查看我的更新并从那里帮助我,我与这个问题斗争了3个多小时,所以留下了一个lil让我发疯@driisand应该在哪个接口中定义T getbyidit tid?甚至还有一个更好的问题:我需要在接口中定义它吗DYou可能希望GetById出现在您的基本存储库界面中。很抱歉,我对这方面非常陌生,您能提供一个完整的示例吗?因为当我尝试实现IEntity时,GetTable不起作用,因为它需要引用类型。IEntity不应该有GetTable方法。它应该在IGenericRepository中,并按照您的模型在GenericRepository中实现。记住要注意通用约束where:part,它在接口和实现中需要相同。请查看我的更新并从那里帮助我,我与这个问题斗争了3个多小时,所以留下了一个lil让我发疯@driissee-see