如何实现通用的GetById(),其中Id可以是各种类型 [英] How to implement generic GetById() where Id can be of various types
问题描述
我试图实现一个通用的 GetById(T id)
方法,它将迎合可能具有不同ID类型的类型。在我的例子中,我有一个实体,它的类型为 int
,并且类型为 string
。
然而,我总是收到一个错误,我不知道为什么:
类型'int'必须是引用类型才能在通用类型的方法IEntity中使用它作为参数'TId'
实体接口:
为了迎合我的领域模型,这些模型可以包含 int 或
字符串 $ b
public interface IEntity< TId> TId:class
{
TId Id {get;组; }
}
实体实现:
public class EntityOne:IEntity< int>
{
public int Id {get;组; }
//其他模型属性...
}
公共类EntityTwo:IEntity< string>
{
public string Id {get;组; }
//其他模型属性...
}
通用存储库接口:
public interface IRepository< TEntity,TId>其中TEntity:class,IEntity< TId>
{
TEntity GetById(TId id);
通用存储库实现:
public abstract class Repository< TEntity,TId> :IRepository< TEntity,TId>
其中TEntity:class,IEntity< TId>
其中TId:class
{
//上下文设置...
public virtual TEntity GetById(TId id)
{
return context.Set< TEntity>()。SingleOrDefault(x => x.Id == id);
}
}
存储库实现:
public class EntityOneRepository:Repository< EntityOne,int>
{
//初始化...
}
public class EntityTwoRepository:Repository< EntityTwo,string>
{
//初始化...
}
您应该从您的 Repository
class中移除对TId的约束。 > public abstract class Repository< TEntity,TId> :IRepository< TEntity,TId>
其中TEntity:class,IEntity< TId>
{
public virtual TEntity GetById(TId id)
{
return context.Set< TEntity>()。Find(id);
}
}
I am trying to implement a generic GetById(T id)
method which will cater for types which may have differing ID types. In my example, I have an entity which has an ID of type int
, and one of type string
.
However, I keep getting an error and I have no idea why:
The type 'int' must be a reference type in order to use it as parameter 'TId' in the generic type of method IEntity
Entity Interface:
To cater for my domain models which can have Id's of type int
or string
.
public interface IEntity<TId> where TId : class
{
TId Id { get; set; }
}
Entity Implementations:
public class EntityOne : IEntity<int>
{
public int Id { get; set; }
// Other model properties...
}
public class EntityTwo : IEntity<string>
{
public string Id { get; set; }
// Other model properties...
}
Generic Repository Interface:
public interface IRepository<TEntity, TId> where TEntity : class, IEntity<TId>
{
TEntity GetById(TId id);
}
Generic Repository Implementation:
public abstract class Repository<TEntity, TId> : IRepository<TEntity, TId>
where TEntity : class, IEntity<TId>
where TId : class
{
// Context setup...
public virtual TEntity GetById(TId id)
{
return context.Set<TEntity>().SingleOrDefault(x => x.Id == id);
}
}
Repository Implementations:
public class EntityOneRepository : Repository<EntityOne, int>
{
// Initialise...
}
public class EntityTwoRepository : Repository<EntityTwo, string>
{
// Initialise...
}
You should remove the constraint on TId from your Repository
class
public abstract class Repository<TEntity, TId> : IRepository<TEntity, TId>
where TEntity : class, IEntity<TId>
{
public virtual TEntity GetById(TId id)
{
return context.Set<TEntity>().Find(id);
}
}
这篇关于如何实现通用的GetById(),其中Id可以是各种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!