系统IDispose没有隐式引用转换

Sha*_*awn 3 c# generics

我有一个UnitOfWork类,我需要编写为Generic但是当我在我的控制器中实例化这个类时,我得到一个构建错误"ProjectName.Models.Person不能用作类型参数TEntity.没有ProjectName的隐式引用转换. Models.Person to System.IDisposable".

这是我的工作单元类,它实现了IDisposiable并期望一个TEntity类类型.此类没有构建错误:

public class UnitOfWork<TEntity> where TEntity : class, IDisposable
{
    private RogDataContext context = new RogDataContext();
    private GenericRepository<TEntity> thisRepository;

     public GenericRepository<TEntity> DataRepository
    {
        get {
            if (this.DataRepository == null)
            {
                this.thisRepository = new GenericRepository<TEntity>(context);
                return thisRepository;
            }
            return thisRepository;
        }
    }

     public void Save()
     {
         context.SaveChanges();
     }

     private bool disposed = false;

     protected virtual void Dispose(bool disposing)
     {
         if (!this.disposed)
         {
             if (disposing)
             {
                 context.Dispose();
             }
         }
         this.disposed = true;
     }

     public void Dispose()
     {
         Dispose(true);
         GC.SuppressFinalize(this);
     }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的MVC控件,它在为Person类声明私有unitOfWork对象时抛出错误:

public class PersonController : Controller
{

    private UnitOfWork<Person> unitOfWork;//<<<< ERROR

    public PersonController()
    {
        this.unitOfWork = new UnitOfWork<Person>();
    }

  //methods ....
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 8

当前的UoW定义要求TEntity(即Person)是一次性的(您已将IDisposable置于泛型类型的约束中)

public class UnitOfWork<TEntity> where TEntity : class, IDisposable
Run Code Online (Sandbox Code Playgroud)

但我认为你希望UoW是一次性的,实体是参考类型.所以,将定义更改为

public class UnitOfWork<TEntity> : IDisposable
    where TEntity : class
Run Code Online (Sandbox Code Playgroud)