【问题标题】:LazyLoading is turned off. Child objects still recursively loaded when .Include() is used.延迟加载已关闭。使用 .Include() 时,子对象仍会递归加载。
【发布时间】:2016-07-27 22:40:43
【问题描述】:

在我们的网络应用程序中,我们使用外观模式。这导致我们使用 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;也将返回 Child2 如图:

var Parent = RepositoryReference.DbContext
                .Parents
                .Include(p => p.Child1);

当钻入父对象时,如图所示检索到 Child2

Parent.Child1.Child2 != null

请注意 Child2 不是虚拟的。

我可以采取哪些进一步的措施来忽略我明确包含的对象的嵌套子级?

谢谢

【问题讨论】:

  • 我认为您在其他地方调用了 child2,请使用 SQL 分析器查看 child2 何时调用。

标签: c# entity-framework lazy-loading


【解决方案1】:

首先请务必配置您的上下文以关闭延迟加载,如下所示:

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 是不再为空。因此,如果这对您来说是正确的,请确保在检索 Child2 时将 parent.Child1.Child2 显式设置为 null 或使用 AsNoTracking()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2011-02-06
    相关资源
    最近更新 更多