【问题标题】:How can I turn on and off lazy loading with EF 5?如何使用 EF 5 打开和关闭延迟加载?
【发布时间】:2013-02-20 17:51:26
【问题描述】:

如果我有以下对象:

public class Application 
{
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<TestAccount> TestAccounts { get; set; }
}

public class TestAccount
{
    public int TestAccountId { get; set; }
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual Application Application { get; set; }
}

EF 映射如下所示:

modelBuilder.Entity<Application>()
    .HasMany(a => a.TestAccounts)
    .WithRequired(t => t.Application)
    .WillCascadeOnDelete(false);

在我的代码的一部分中,我想检索应用程序的数据并拥有 它返回 TestAccount 数据。

在我的代码的另一部分,我想检索应用程序的数据和 让它不返回 TestAccount 数据。

有没有办法可以通过 LINQ 或其他方式实现这一点?

【问题讨论】:

    标签: linq entity-framework entity-framework-4.1


    【解决方案1】:

    这里已经回答了这个问题:Disable lazy loading by default in Entity Framework 4

    基本上,在 DbContext 的构造函数中,只需添加以下内容:

    this.Configuration.LazyLoadingEnabled = false;
    

    我希望这会有所帮助。

    编辑

    另外,如果你想知道以后如何手动加载它,使用Include()应该是一件简单的事情,像这样:

    var query = context.Application.Include(x =&gt; x.TestAccounts).ToList()

    【讨论】:

    • 非常感谢。我现在有另一个问题。将发布并希望有人可以提供帮助。
    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多