我如何打开和关闭延迟加载EF 5



如果我有以下对象:

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或其他方式实现这一点吗?

这个问题在这里已经有了答案:在Entity Framework 4中默认禁用延迟加载

基本上,在DbContext的构造函数中,只需添加以下内容:
this.Configuration.LazyLoadingEnabled = false;

我希望这对你有帮助。

编辑

同样,如果你想知道如何手动加载它,它应该是一个简单的问题使用Include()像这样:

var query = context.Application.Include(x => x.TestAccounts).ToList()

最新更新