【问题标题】:DbContextScope with Generic Repository具有通用存储库的 DbContextScope
【发布时间】:2016-06-22 07:59:45
【问题描述】:

我正在使用 here 描述的 DbContextScope

在他关于如何在其实例化的类之外获取 dbcontext 的示例中,Mehdi 写道:

public class UserRepository : IUserRepository {
    private readonly IAmbientDbContextLocator _contextLocator;

    public UserRepository(IAmbientDbContextLocator contextLocator)
    {
        if (contextLocator == null) throw new ArgumentNullException("contextLocator");
        _contextLocator = contextLocator;
    }

    public User Get(Guid id)
    {
        return _contextLocator.Get<MyDbContext>.Set<User>().Find(id);
    } 
}

但是,如果我要使用通用存储库,比如说

public abstract class RepositoryBase<T> : IRepository<T> where T : class, IDomainEntity
{
    private readonly DbSet<T> set;

    private IAmbientDbContextLocator contextLocator;

    protected RepositoryBase(IAmbientDbContextLocator ctxLocator)
    {
        if (ctxLocator == null) throw new ArgumentNullException(nameof(ctxLocator));
        contextLocator = ctxLocator;
    }

    public T Get(Guid id)
    {
        //return _contextLocator.Get<MyDbContext>.Set<T>().Find(userId);
    }
}

那么 dbset 应该如何解决呢?如何在 Get 方法中使用“MyDbContext”? 我确实有多个上下文。

【问题讨论】:

    标签: c# entity-framework generics repository-pattern dbcontext


    【解决方案1】:
       public abstract class RepositoryBase<T, TDbContext> : IRepository<T> where T : IDomainEntity where TDbContext : DbContext
        {
            private readonly DbSet<T> _dbset;
            private readonly IAmbientDbContextLocator _contextLocator;
    
            protected RepositoryBase(IAmbientDbContextLocator ctxLocator)
            {
                if (ctxLocator == null) throw new ArgumentNullException(nameof(ctxLocator));
                _contextLocator = ctxLocator;
                _dbset = _contextLocator.Get<TDbContext>.Set<T>();
            }
    
            protected DbSet<T> DbSet { get { return _dbset; } }
            public T Get(Guid id)
            {
                return DbSet.Find(id);
            }
        }
    

    如果您不想要TDbContext,您可以在contextlocator 旁边的构造函数上发送DbContext。但是他强迫你使用DbContextScope,我没有阅读所有文章但我们不要打破他的逻辑。

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多