如何实现通用的GetById(),其中Id可以是各种类型

我正在尝试实现一个通用的GetById(T id)方法,该方法将满足可能具有不同ID类型的类型。 在我的示例中,我有一个实体,其ID类型为int ,类型为string

但是,我一直收到错误,我不明白为什么:

类型’int’必须是引用类型才能在方法IEntity的generics类型中将其用作参数’TId’

实体接口:

为了满足我的域模型,可以使用类型为intstring Id。

 public interface IEntity where TId : class { TId Id { get; set; } } 

实体实施:

 public class EntityOne : IEntity { public int Id { get; set; } // Other model properties... } public class EntityTwo : IEntity { public string Id { get; set; } // Other model properties... } 

通用存储库接口:

 public interface IRepository where TEntity : class, IEntity { TEntity GetById(TId id); } 

通用存储库实现:

 public abstract class Repository : IRepository where TEntity : class, IEntity where TId : class { // Context setup... public virtual TEntity GetById(TId id) { return context.Set().SingleOrDefault(x => x.Id == id); } } 

存储库实现:

  public class EntityOneRepository : Repository { // Initialise... } public class EntityTwoRepository : Repository { // Initialise... } 

您应该从Repository类中删除TId上的约束

 public abstract class Repository : IRepository where TEntity : class, IEntity { public virtual TEntity GetById(TId id) { return context.Set().Find(id); } } 
 public interface IEntity where TId : class { TId Id { get; set; } } 

where TId : class约束的地方要求每个实现都有一个从对象派生的Id,对于像int这样的值类型是不正确的。

这是错误消息告诉您的内容: The type 'int' must be a reference type in order to use it as parameter 'TId' in the generic type of method IEntity

只需从IEntity删除IEntity

对你的问题:
我正在尝试实现一个通用的GetById(T id)方法,该方法将满足可能具有不同ID类型的类型。 在我的示例中,我有一个实体,其ID类型为int,类型为string。

  public virtual TEntity GetById(TId id) { return context.Set().SingleOrDefault(x => x.Id == id); } 

对于通用参数,只需制作如上所述的通用方法