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

Tom*_*uke 12 c# generics asp.net-mvc repository-pattern

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

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

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

实体接口:

为了满足我的域名模型,这些模型可以具有Id类型intstring.

public interface IEntity<TId> where TId : class
{
    TId Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

实体实施:

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...
}
Run Code Online (Sandbox Code Playgroud)

通用存储库接口:

public interface IRepository<TEntity, TId> where TEntity : class, IEntity<TId>
{
    TEntity GetById(TId id);
}
Run Code Online (Sandbox Code Playgroud)

通用存储库实现:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

存储库实现:

 public class EntityOneRepository : Repository<EntityOne, int>
    {
        // Initialise...
    }

    public class EntityTwoRepository : Repository<EntityTwo, string>
    {
        // Initialise...
    }
Run Code Online (Sandbox Code Playgroud)

Que*_*ger 8

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Jür*_*ock 5

public interface IEntity<TId> where TId : class
{
    TId Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

where TId : class约束要求每个实现有从对象,它是不是值类型如int真正派生的标识。

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

只需where TId : classIEntity<TId>