简体   繁体   中英

There is no implicit reference conversion to system IDispose

I have a UnitOfWork class that I need to code as Generic but when I instantiate this class in my controller I get a build error "The ProjectName.Models.Person cannot be used as type parameter TEntity. There is no implicit reference conversion from ProjectName.Models.Person to System.IDisposable".

This is my Unit of Work class that implements IDisposiable and expects a TEntity class type. There are no build error on this class:

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

This is my MVC Control that is throwing an error when declaring the private unitOfWork object for the Person class:

public class PersonController : Controller
{

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

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

  //methods ....

Current UoW definition requires TEntity (ie Person) to be disposable (you have put IDisposable to constraints of generic type)

public class UnitOfWork<TEntity> where TEntity : class, IDisposable

But I think you want UoW to be disposable, and entity to be of reference type. So, change definition to

public class UnitOfWork<TEntity> : IDisposable
    where TEntity : class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM