2

如何从 DbContext 中检索未提交的实体?

考虑以下测试:

    [Test]
    public void AddAndRetrieveUncommittedTenant()
    {
        _tenantRepository.Create("testtenant");
        var tenant = _tenantRepository.GetTenantByName("testtenant");

        Assert.AreEqual("testtenant", tenant.Name);
    }

测试失败,因为tenantis null

中间有很多具体的业务代码,但归结为:

在我的Repository类中,方法GetTenantByName最终调用了GetAll方法。

    public IQueryable<TEntity> GetAll()
    {
        return DbSet.AsQueryable();
    }

    private IDbSet<TEntity> DbSet
    {
        get { return Context.Set<TEntity>(); }
    }

在扩展的类上,DbContext我有以下方法:

    public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
    {
        return base.Set<TEntity>();
    }

当我设置断点时,return base.Set<TEntity>();我可以看到该实体在存储库中可用(通过local属性)。


在此处输入图像描述


如何从我的存储库中检索未提交的实体?

4

2 回答 2

4

我使用派生自的类DbContext并添加以下方法来访问已更改的实体。这也应该告诉您如何访问您的更改实体DbContext

public virtual IEnumerable<DbEntityEntry> ChangedEntities
{
    get { return base.ChangeTracker.Entries().Where(e => e.State != EntityState.Unchanged); }
}

ChangeTracker是 上的公共属性DbContext,因此您也可以从外部类访问此属性:

var dirtyEntities = myDbContext.ChangeTracker.Entries().Where(e => e.State != EntityState.Unchanged);

或者,如果您想查找已添加/修改的实体等,您可以获得更具体的信息:

var addedEntities = myDbContext.ChangeTracker.Entries().Where(e => e.State == EntityState.Added);
var modifiedEntities = myDbContext.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified);

等等。

于 2013-02-25T18:22:15.383 回答
2

只需执行以下简单交易:

using (var scope = new TransactionScope(TransactionScopeOption.Required,
                        new TransactionOptions()
                        {
                            IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
                        }))
{
    var employees = _context.Employees.ToList();
    scope.Complete();
}

如果您想同步获取数据,请将 TransactionScopeAsyncFlowOption.Enabled 添加到上面的代码中:

using (var scope = new TransactionScope(TransactionScopeOption.Required,
                        new TransactionOptions()
                        {
                            IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
                        },
                        TransactionScopeAsyncFlowOption.Enabled))
{
    var employees = await _context.Employees.ToListAsync();
    scope.Complete();
}

为简单起见,您可以对上述事务有自己的扩展方法:

public static async Task<List<T>> ToListWithNoLockAsync<T>(this IQueryable<T> query, CancellationToken cancellationToken = default)
{
    List<T> result = default;
    using (var scope = new TransactionScope(TransactionScopeOption.Required,
                            new TransactionOptions()
                            {
                                IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
                            },
                            TransactionScopeAsyncFlowOption.Enabled))
    {
        result = await query.ToListAsync(cancellationToken);
        scope.Complete();
    }
    return result;
}

并像下面这样简单地使用它:

var employees = dbContext.Employees
                          .AsNoTracking()
                          .Where(a => a.IsDelete == false)
                          .ToListWithNoLockAsync();
于 2020-12-20T08:36:51.637 回答