当我执行以下语句时,我很难理解为什么查询会重新调整此错误:
SelectFor(x => x.Id == id, true, false, "Scope.Hiring.Scopes")
上述语句中的字符串是要包含的实体。
SelectFor 方法:
public virtual TEntity SelectFor(Expression<Func<TEntity, bool>> predicate, bool noTracking = true, bool selectInactiveItems = false, params string[] entitiesToLoad)
{
var query = this.LoadRelatedEntities(this.transaction.Context.Set<TEntity>().AsQueryable(), entitiesToLoad);
query = query.Where(x => x.OwnerId == ownerId).Where(predicate);
if (!selectInactiveItems)
{
query = query.Where(x => x.Active);
}
if (noTracking)
{
query = query.AsNoTracking();
}
return query.FirstOrDefault();
}
包含方法
protected IQueryable<TEntity> LoadRelatedEntities(IQueryable<TEntity> query, params string[] entitiesToLoad)
{
if (entitiesToLoad != null && entitiesToLoad.Count() > 0)
{
foreach (var entityToLoad in entitiesToLoad)
{
query = query.Include(entityToLoad);
}
}
return query;
}
这看起来很容易做,但它需要我的时间和耐心。
最佳答案
您在查询中使用了 AsNoTracking
。因此,EF 不会跟踪它具体化的实体。这意味着当它从数据库中获取 Scope
时,它将为每个“相同”的范围创建多个对象。由于循环查询模式 Scope.Hiring.Scopes
,这里肯定会发生这种情况。
但是,EF 确实在构建对象图时执行关系修复,即它使用具体化的实体填充导航属性,以便 f.e.每个 Scope
对象都有一个 Hiring
引用。在执行此操作时,我认为它会尝试将重复的 Scope
对象分配给已经具有该对象的 Hiring
对象。
解决方案:删除 AsNoTracking
或删除循环查询:Scope.Hiring
而不是 Scope.Hiring.Scopes
。
关于c# - '已加载角色名为 X 的 RelatedEnd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46038016/