无法从存储库转换为IRepository UOW存储库模式
问题描述:
我正在尝试使用存储库模式和工作单元的MVC项目。无法从存储库转换为IRepository UOW存储库模式
以下是从我的InitOfWork
public interface IUnitOfWork
{
IRepository<User> UserRepository { get; }
void Save();
}
,这是从的UnitOfWork
public class UnitOfWork:IUnitOfWork, IDisposable
{
private JNContext context = new JNContext();
private bool disposed = false;
private IRepository<User> userRepository;
public IRepository<User> UserRepository
{
get
{
if (this.userRepository == null)
{
this.userRepository = new Repository<User>(this.context);
}
return this.userRepository;
}
}
public void Save()
{
this.context.SaveChanges();
}}
中的UnitOfWork下面一行生成错误“无法隐从库转换为IRepository
this.userRepository = new Repository<User>(this.context);
我错过了什么。我无法找到答案,而且我一整天都陷入困境。
答
尝试这样的事情
public interface IRepository<T> where T : class
{
IQueryable<T> Entities { get; }
void Remove(T entity);
void Add(T entity);
}
public class GenericRepository<T> : IRepository<T> where T : class
{
private readonly MyDbContext _dbContext;
private IDbSet<T> _dbSet => _dbContext.Set<T>();
public IQueryable<T> Entities => _dbSet;
public GenericRepository(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public void Remove(T entity)
{
_dbSet.Remove(entity);
}
public void Add(T entity)
{
_dbSet.Add(entity);
}
}
发现它这里的好文章:https://medium.com/@utterbbq/c-unitofwork-and-repository-pattern-305cd8ecfa7a
你确定,该资源库实现IRepository? – wheeler
@wheeler:不,它不是。我有**公开课仓库其中TEntity:class **。我需要实现** IRepository **吗?是否可以依赖注入 –
是的,你需要实现'IRepository'。在'Repository'中。编译器无法解决这个问题。 – RedgoodBreaker