C# 延迟加载子实体集合
我有一个产品实体和一个子产品实体:C# 延迟加载子实体集合,c#,entity-framework,lazy-loading,C#,Entity Framework,Lazy Loading,我有一个产品实体和一个子产品实体: public class Product { public virtual ICollection<ProdAttribute> Attributes { get; set; } public virtual ICollection<ChildProduct> Children { get; set; } public string ItemID { get; set; } public string I
public class Product
{
public virtual ICollection<ProdAttribute> Attributes { get; set; }
public virtual ICollection<ChildProduct> Children { get; set; }
public string ItemID { get; set; }
public string ItemName { get; set; }
}
public class ChildProduct
{
public virtual ICollection<ProdAttribute> Attributes { get; set; }
public int DisplayOrder { get; set; }
public string ItemID { get; set; }
public string ItemName { get; set; }
public virtual Product Parent { get; set; }
public string ParentItemID { get; set; }
public string Size { get; set; }
}
现在我希望孩子们也包括属性,所以我尝试使用
return _axaptaContext.Products
.Include(x => x.Children)
.Include("Children.Attributes")
.Include(x => x.Attributes);
但这会导致查询超时。当我尝试调用时,如何延迟加载子对象的属性:
product.Children.Attribtutes
它只返回null。我发现的所有关于延迟加载的信息都表明,如果我将属性标记为虚拟属性,那么属性应该是延迟加载的。首先,您不需要调用
。Include(“Children.attributes”)
到lazy加载,而是用于急切地加载实体
只需确保在上下文对象上将LazyLoadingEnabled
&ProxyCreationEnabled
设置为true。现在,当您调用属性sql上的get来获取实体时,该实体将自动被激发,并且您将得到填充的对象
context.Configuration.ProxyCreationEnabled = true;
context.Configuration.LazyLoadingEnabled = true;
注意:要延迟加载的属性需要是虚拟的。我已经做了
LazyLoadingEnabled
但没有意识到ProxyCreationEnabled
也需要是真的。谢谢,这很有效!
context.Configuration.ProxyCreationEnabled = true;
context.Configuration.LazyLoadingEnabled = true;