gpt4 book ai didi

c# - 具有通用存储库的 DbContextScope

转载 作者:行者123 更新时间:2023-11-30 23:28:44 24 4
gpt4 key购买 nike

我正在使用描述的 DbContextScope here

在他的示例中,如何在实例化的类之外获取 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”?我确实有多个上下文。

最佳答案

   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,我没有阅读所有文章,但我们不要打破他的逻辑。

关于c# - 具有通用存储库的 DbContextScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35866270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com