2011-09-23 66 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:這非常有用,謝謝你的評論。 –