延迟加载已关闭。使用 .Include() 时,子对象仍会递归加载。

LazyLoading is turned off. Child objects still recursively loaded when .Include() is used.

在我们的网络应用程序中,我们使用外观模式。这导致我们利用 Automapper 在对象层 DAL <-> DTO <-> ViewModels 之间进行转换。

我禁用了LazyLoading,大部分都生效了。 然而,一些嵌套对象在没有明确添加到“.include”语句中的情况下被包含在内。

示例:

public class Parent {
    public Guid? Child1Id{ get; set; }

    [ForeignKey("Child1Id")]
    public Child1 Child1 { get; set; }
}

public class Child1 {
    public Guid? Child2Id{ get; set; }

    [ForeignKey("Child2Id")]
    public Child2 Child2 { get; set; }
}

public class Child2 {
    public string Name { get; set; }
}

现在尝试检索 Parent 和 Child1;还将 return 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);