Entity framework 延迟加载在新保存的对象上不起作用(从保存对象的上下文中获取对象时)

Entity framework 延迟加载在新保存的对象上不起作用(从保存对象的上下文中获取对象时),entity-framework,entity-framework-4.1,Entity Framework,Entity Framework 4.1,我有这门课 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; } } 问题是,虚拟财产所有

我有这门课

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对象引用异常

comment.Owner.Name
在保存对象后立即调用此函数时(从DbContext的同一实例) 在一个新的环境下,它将起作用


有人知道这件事吗?

这是因为您使用构造函数创建了
注释。这意味着注释实例没有代理,不能使用延迟加载。您必须在
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绑定器(使用默认构造函数),您可以像这样显式引用:context.Entry(comment.reference(x=>x.Owner.Load();m、 班纳特:那很有用,谢谢你的评论。