【问题标题】:lazy loading not working when on new saved objects, (when getting them from the context that saved them)延迟加载在新保存的对象上不起作用,(从保存它们的上下文中获取它们时)
【发布时间】:2011-09-24 03:57:32
【问题描述】:

我有这门课

public class Comment
{      
    public long Id { get; set; }
    public string Body { get; set; }
    public long OwnerId { get; set; }
    public virtual Account Owner { get; set; }
    public DateTime CreationDate { get; set; }
}

问题是虚拟财产所有者是我在做时得到null object reference exception

comment.Owner.Name

在保存对象后立即调用此方法(来自同一 DbContext 实例) 使用新的上下文将起作用

有人知道吗?

【问题讨论】:

    标签: entity-framework entity-framework-4.1


    【解决方案1】:

    那是因为你用构造函数创建了Comment。这意味着 Comment 实例没有被代理,它不能使用延迟加载。您必须在DbSet 上使用Create 方法来获取Comment 的代理实例:

    var comment = context.Comments.Create();
    // fill comment
    context.Comments.Add(comment);
    context.SaveChanges();
    string name = comment.Owner.Name; // Now it should work because comment instance is proxied
    

    【讨论】:

    • 对于寻找不这样做的方法的其他人,但是说,使用 MVC Binder(使用默认构造函数),您可以像这样显式引用: context.Entry(comment).Reference (x => x.Owner).Load();
    • m.t.bennett:这非常有用,谢谢您的评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多