错误 - “TEntity”类型必须是引用类型才能将其用作参数

时间:2017-02-08 09:48:48

标签: c# generics repository-pattern

public class Repository<TEntity> : IRepository<TEntity> where TEntity : Entity
{
    private IDbSet<TEntity> GetSet()
    {
       return _unitOfWork.CreateSet<TEntity>();
    }
}

在上面的代码中,我在 GetSet()

上遇到以下错误
  

错误1'TEntity'类型必须是引用类型才能在泛型类型或方法'System.Data.Entity.IDbSet'中使用它作为参数'TEntity':E:\ Pradeep \ Workshop \ WebAPI \ Extras \ DDD \ DDD.WebAPI \ 4.DDD.Infrastructure \ Repository \ Repository.cs 44 33 4.DDD.Infrastructure

2 个答案:

答案 0 :(得分:1)

Repository课程中,您对类型参数TEntity有一般约束:

where TEntity : Entity

在实体框架中,实体必须是类(由where T : class约束强制执行)。由于您收到错误,Entity不是一个类。唯一的可能性是它是struct或接口。根据这一点,您的问题的解决方案完全不同:

  1. 如果Entitystruct,则需要将其更改为class。 EF不允许您使用值类型创建实体集。
  2. 如果Entity是一个接口,则需要将引用类型约束转发到您的存储库类(并且可能在您重新命名时将接口重命名为IEntity以符合.NET编码指南)。
  3. 如果Entity是一个界面,请输入以下代码:

    public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, Entity
    {
        //...
    }
    

答案 1 :(得分:0)

如果将class添加到where语句,则编译器将知道它只能是引用类型。像这样:

public class Repository<TEntity> : IRepository<TEntity> where TEntity : Entity, class
{
    // ...
}
相关问题