【问题标题】:Lazy load sub entity collection懒加载子实体集合
【发布时间】:2015-11-18 21:21:09
【问题描述】:

我有一个产品实体和一个子产品实体:

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

它只是返回空值。我发现的关于延迟加载的所有内容都表明,如果我将属性标记为虚拟属性,则它们应该是延迟加载的

【问题讨论】:

    标签: c# entity-framework lazy-loading


    【解决方案1】:

    首先你不需要调用.Include("Children.Attributes")lazy 加载,而是eager 加载实体。

    只需确保您已在上下文对象上将 LazyLoadingEnabledProxyCreationEnabled 设置为 true。现在,当您调用属性 sql 上的 get 来获取实体时,实体会自动被触发,并且您将填充对象。

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

    注意:要延迟加载的属性必须是虚拟的。

    【讨论】:

    • 我已经完成了LazyLoadingEnabled,但没有意识到ProxyCreationEnabled 也必须是真的。谢谢这工作!
    猜你喜欢
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2017-07-30
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 2011-10-20
    相关资源
    最近更新 更多