2011-09-23 64 views
6

我有这个类(从保存它们的背景下获得它们时)延迟加载不工作时,新保存的对象,

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的同一实例)

一个新的上下文将工作

的大家知道这件事吗?

回答

18

那是因为你用构造函数创建了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 
+0

感谢这个,非常简洁,给点意见! –

+1

对于其他寻找解决方法的人不要这样做,但是使用MVC Binder(使用默认构造函数)来说,你可以像这样明确地引用: context.Entry(comment).Reference(x => x .Owner).Load(); –

+0

m.t.bennett:这非常有用,谢谢你的评论。 –