【问题标题】:How to implement generic GetById() where Id can be of various types如何实现通用 GetById() ,其中 Id 可以是各种类型
【发布时间】:2021-06-09 20:11:39
【问题描述】:

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

但是,我不断收到错误消息,我不知道为什么:

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

实体接口:

为了迎合我的域模型,这些模型的 ID 类型为 int 或 string。

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

【问题讨论】:

  • 为什么将TId 限制为class 类型?这不适用于int(错误消息非常清楚)。 class 表示泛型约束中的“引用类型”。

标签: c# asp.net-mvc generics repository-pattern


【解决方案1】:

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

【讨论】:

  • 此建议解决了引用类型错误,但是,我现在在尝试按 Id 执行匹配时收到 Operator == cannot be applied to operands of type TId and TId 错误
  • 事实证明,如果我使用 .Find(id) 而不是 .SingleOrDefault(x =&gt; x.Id == id),它可以正常工作。我希望它在这个方法后面做同样的事情,所以不知道为什么.Find() 是有效的。
  • 对于.SingleOrDefault(x=&gt;x.Id == id)错误,你也可以使用.SingleOrDefault(x=&gt;x.Id.Equals(id))
【解决方案2】:
public interface IEntity<TId> where TId : class
{
    TId Id { get; set; }
}

where TId : class 约束要求每个实现都有一个从 object 派生的 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&lt;TId&gt; 中删除约束where TId : class

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 2020-05-19
      • 2013-10-25
      • 1970-01-01
      • 2022-10-02
      • 2013-03-09
      • 1970-01-01
      相关资源
      最近更新 更多