我正在尝试使用存储库模式和工作单元的MVC项目。
以下内容来自我的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中的以下行生成错误&#39;无法从存储库隐式转换为IRepository
this.userRepository = new Repository<User>(this.context);
我错过了什么。我找不到答案而且整天都陷入困境。
答案 0 :(得分:0)
尝试这样的事情
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