延迟加载子实体集合

时间:2015-11-18 13:01:53

标签: 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 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(x => x.Attributes);

现在我希望孩子们也包含这些属性,所以我尝试使用

        return _axaptaContext.Products
            .Include(x => x.Children)
            .Include("Children.Attributes")
            .Include(x => x.Attributes);

但是这会导致查询超时。当我试图调用时,如何延迟加载子项的属性:

product.Children.Attribtutes

它只返回null。我发现的关于延迟加载的所有内容都说如果我将它们标记为虚拟

,属性应该是延迟加载的

1 个答案:

答案 0 :(得分:2)

首先,您不需要将.Include("Children.Attributes")调用延迟加载,而是用于急切加载实体。

确保您已设置LazyLoadingEnabled&amp;对于上下文对象,ProxyCreationEnabled为true。现在当你调用属性sql上的get来获取实体时会自动被触发,你将获得对象的填充。

context.Configuration.ProxyCreationEnabled = true;
context.Configuration.LazyLoadingEnabled = true;

注意:您想要延迟加载的属性需要是虚拟的。

相关问题