C# 懒散的加载被关闭。使用.Include()时仍递归加载子对象。

C# 懒散的加载被关闭。使用.Include()时仍递归加载子对象。,c#,entity-framework,lazy-loading,C#,Entity Framework,Lazy Loading,在我们的web应用程序中,我们使用Facade模式。这导致我们使用Automapper在对象层之间转换DAL DTO视图模型 我已经禁用了懒散加载功能,并且它在很大程度上起到了作用。 但是,有些嵌套对象被包括在内,而没有在“.include”语句中显式添加它们 例子: 现在,任何检索父项和子项的尝试1;也将返回Child2 如图所示: var Parent = RepositoryReference.DbContext .Parents

在我们的web应用程序中,我们使用Facade模式。这导致我们使用Automapper在对象层之间转换DAL DTO视图模型

我已经禁用了懒散加载功能,并且它在很大程度上起到了作用。 但是,有些嵌套对象被包括在内,而没有在“.include”语句中显式添加它们

例子: 现在,任何检索父项和子项的尝试1;也将返回Child2 如图所示:

var Parent = RepositoryReference.DbContext
                .Parents
                .Include(p => p.Child1);
钻取父对象时,将检索Child2,如图所示

Parent.Child1.Child2 != null
请注意Child2不是虚拟的

我可以采取哪些进一步的操作来忽略我显式包含的对象的嵌套子对象


谢谢

首先,请确保按如下方式配置您的上下文以关闭延迟加载:

public DbContext()
    : base("Name = ConntectionName")
{
    this.Configuration.ProxyCreationEnabled = false;
    this.Configuration.LazyLoadingEnabled = false;
}
正如@MahdiFarhani所述,另一个原因可能是您在同一范围内加载具有相同id的Child2。设想以下场景:

var child2Id = ......;
Child2 child2 = RepositoryReference
    .DbContext
    .Child2s
    .FirstOrDefault(m => m.Id == child2Id);

Parent Parent = RepositoryReference
    .DbContext
    .Parents
    .Include(p => p.Child1);
如果在上述场景中parent.Child1.Child2等于child2Id,则它们将自动关联,并且parent.Child1.Child2不再为空。因此,如果这对您是正确的,请确保显式地将parent.Child1.Child2设置为null,或者在检索Child2时使用AsNoTracking()

Child2 child2 = RepositoryReference
    .DbContext
    .Child2s
    .AsNoTracking() // Add this line to not keep Child2 in context
    .FirstOrDefault(m => m.Id == child2Id);

我想您应该在其他地方调用child2,请使用SQL探查器检查child2何时调用。
Child2 child2 = RepositoryReference
    .DbContext
    .Child2s
    .AsNoTracking() // Add this line to not keep Child2 in context
    .FirstOrDefault(m => m.Id == child2Id);