【问题标题】:Cannot convert from Repository to IRepository UOW Repository pattern无法从存储库转换为 IRepository UOW 存储库模式
【发布时间】:2017-09-03 18:51:26
【问题描述】:

我正在尝试使用存储库模式和工作单元的 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 中的以下行生成错误“无法从 Repository 隐式转换为 IRepository”

this.userRepository = new Repository<User>(this.context);

我错过了什么。我找不到答案,一整天都被卡住了。

【问题讨论】:

  • 你确定 Repository 实现了 IRepository 吗?
  • @wheeler :不,不是。我有 public class Repositorywhere TEntity:class。我需要实施 IRepository 吗?依赖注入是否可行
  • 是的,您需要实现IRepository。在Repository。没有这个,编译器无法弄清楚。

标签: asp.net asp.net-mvc repository-pattern unit-of-work


【解决方案1】:

试试这样的

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多