【发布时间】:2013-08-12 22:58:28
【问题描述】:
您必须“触摸”多少导航属性才能确保延迟加载集合?
我正在使用 Entity Framework 5.0 并开启了延迟加载。考虑一个简单的类:
public class MyResource
{
string name {get;set;}
public virtual ICollection<ResourceEvent> ResourceEvents{ get; set; }
}
当我在集合上设置“foreach”时,我想避免单独检索集合中的每个对象。
using(context = new MyDBContext)
{
MyResource aresource = context.MyResources.Where(a=>a.Name==myname).Single();
//now I want to lazy load the ResourceEvents collection
if(aresource.MyResources!=null) // will this load collection?
{
List<ResourceEvent> alist = aresource.MyResources.ToList();//or must I add this?
foreach(ResourceEvent re in alist)// (or in aresource.MyResources)
{
//do something
}
}
}
我知道我可以使用 Include(),但假设 MyResource 对象来自我们不知道是否已检索到集合的其他地方。
【问题讨论】:
标签: c# entity-framework lazy-loading