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

问题描述 投票:12回答:3

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

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

类型'int'必须是引用类型才能在方法IEntity的泛型类型中将其用作参数'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...
    }
c# asp.net-mvc generics repository-pattern
3个回答
7
投票

您应该从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);
    }
}

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

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

这就是错误消息告诉你的:qazxsw poi

只需从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 : class


1
投票

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

IEntity<TId>

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

© www.soinside.com 2019 - 2024. All rights reserved.