C# 实体框架6-从导航集合获取延迟IQueryable
我有一个简单的实体,具有以下关系:C# 实体框架6-从导航集合获取延迟IQueryable,c#,asp.net,entity-framework-6,lazy-loading,C#,Asp.net,Entity Framework 6,Lazy Loading,我有一个简单的实体,具有以下关系: class Foo { public int BarId { get; set; } public virtual Bar { get; set; } public boolean Active { get; set; } public boolean Condition{ get; set; } } class Bar { public virtual ICollection<Foo> Foos { g
class Foo
{
public int BarId { get; set; }
public virtual Bar { get; set; }
public boolean Active { get; set; }
public boolean Condition{ get; set; }
}
class Bar
{
public virtual ICollection<Foo> Foos { get; set; }
}
在执行foreach循环之前,延迟执行不会发生吗?在此之前,我没有看到您的代码在结果集上迭代。您如何知道foo项已加载到doSomething的第一行?@Agalo No,当通过
bar.Foos
访问时,它将延迟加载。我在调试SQL日志时看到它。简短的回答是-您不能这样做。您需要访问context.bar
或context.Foos
(最好是后者)
public void doSomething(Bar bar, bool condition)
{
// even with lazy loading all Foo's have been loaded here
IQueryable<Foo> foos = bar.Foos.AsQueryable().Where(f => f.Active);
if (condition)
foos = foos.Where(f => f.Condition);
// I want to defer loading until all filters are applied
foreach (Foo foo in foos)
{
// do something with foo
}
}
IRepository<Foo> repoFoo = uow.getRepository<Foo>();
IQueryable<Foo> queryFoo = repoBar.getQuery().Where(f => f.BarID = bar.ID && bar.Active)
// check condition