几天来,我一直在努力从存储库中检索我的实体(DbContext
)。
我试图在原子动作中保存所有实体。因此,不同的实体一起代表了对我有价值的东西。如果所有实体都是“有效”,那么我可以将它们全部保存到数据库中。实体“a”已存储在我的存储库中,需要检索以“验证”实体“b”。
这就是问题出现的地方。我的存储库依赖于 DbSet<TEntity>
适用于Linq2Sql的类(Include()
导航属性,例如)。但是, DbSet<TEntity>
不包含处于“已添加”状态的实体。
所以我(据我所知)有两个选择:
- 使用
ChangeTracker
查看哪些实体可用,并根据它们将它们查询到一个集合中EntityState
。 - 使用
DbSet<TEntity>.Local
属性。
该 ChangeTracker
似乎需要一些额外的努力来让它以一种方式工作,以便我可以使用Linq2Sql Include()
导航属性例如
该 DbSet<TEntity>.Local
对我来说似乎有点奇怪。它可能只是名字。我只是读了一些表现不佳的东西(比DbSet <>本身慢)。不确定这是否是虚假陈述。
具有重要EntityFramework经验的人能否对此有所了解?什么是“明智”的道路?或者我看到鬼魂,我应该总是使用 .Local
属性?
使用代码示例更新:
出了什么问题的一个例子
public void AddAndRetrieveUncommittedTenant()
{
_tenantRepository = new TenantRepository(new TenantApplicationTestContext());
const string tenantName = "testtenant";
// Create the tenant, but not call `SaveChanges` yet until all entities are validated
_tenantRepository.Create(tenantName);
//
// Some other code
//
var tenant = _tenantRepository.GetTenants().FirstOrDefault(entity => entity.Name.Equals(tenantName));
// The tenant will be null, because I did not call save changes yet,
// and the implementation of the Repository uses a DbSet<TEntity>
// instead of the DbSet<TEntity>.Local.
Assert.IsNotNull(tenant);
// Can I safely use DbSet<TEntity>.Local ? Or should I play
// around with DbContext.ChangeTracker instead?
}
我想如何使用我的一个例子 Repository
在我的 Repository
我有这个方法:
public IQueryable<TEntity> GetAll()
{
return Context.Set<TEntity>().AsQueryable();
}
我以这种方式在业务代码中使用它:
public List<Case> GetCasesForUser(User user)
{
return _repository.GetAll().
Where(@case => @case.Owner.EmailAddress.Equals(user.EmailAddress)).
Include(@case => @case.Type).
Include(@case => @case.Owner).
ToList();
}
这主要是我更喜欢坚持的原因 DbSet
像变量。我需要灵活性 Include
导航属性。如果我用的话 ChangeTracker
我检索一个实体 List
,这不允许我在以后的时间点延迟加载相关的实体。
如果这接近难以理解的崩溃* t,那么请告诉我,以便我可以改进这个问题。我迫切需要一个答案。
很多提前!