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

How to implement generic GetById() where Id can be of various types

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

但是,我一直收到错误,我不知道为什么:

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

实体接口:

为了满足我的域模型,它可以具有 intstring 类型的 ID。

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

实体实现:

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...
}

通用存储库接口:

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

通用存储库实现:

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);
    }
}

存储库实现:

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

    public class EntityTwoRepository : Repository<EntityTwo, string>
    {
        // Initialise...
    }

您应该从 Repository class

中删除对 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);
    }
}

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

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

对于泛型参数,只需像上面那样制作一个泛型方法

public interface IEntity<TId> 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<TId>

中删除约束 where TId : class