2015-06-05 55 views
1

我有這是導致NullReferenceException的代碼。我希望延遲加載可以在評估lambda時跳入數據庫並轉到提取導航屬性(最後一行)的數據庫。我直接使用Id解決了這個問題,但我很好奇,如果任何人都可以將我指向任何解釋這裏發生的事情的文檔,以及爲什麼這不起作用。Linq Lambda和EF懶惰加載 - NullReferenceException

  using (var context = new TestEntities()) 
      { 
       var entity = context.Entities.First(); 

       entity.NavigationPropertyId = 24; // This is a valid id, i.e. there is a record with Id 24 in the database 

       var otherEntity = context 
           .OtherEntities 
           .SingleOrDefault(x => 
            (x.NavigationPropertyId == entity.NavigationProperty.Id)); // << This raises the NullReferenceException 
      } 
+0

在一行上你'entity.NavigationPropertyId =','後entity.NavigationProperty.Id',即'Id'成爲NavigationProperty'的'屬性第二種情況。這是錯誤還是問題的原因? –

+0

顯然,'x'爲'null',或'entity.NavigationProperty'爲'null'。 –

+0

Lasse,這不是重複的。我知道NullReferenceException是什麼。 X不能爲null,因爲它是lambda表達式的謂詞。 NavigationProperty顯然是空的,但我希望它是懶加載的,因此我的問題。 – Klaws86

回答

0

好,很多奇怪的事情

//with First, your entity could be almost anything, and it's NavigationProperty could perfectly be null. 
var entity = context.Entities.First(); 
//now you set its foreign key value ??? this won't affect an eventual navigation property, if you don't save the entity... 
entity.NavigationPropertyId = 24; 

然後,在的SingleOrDefault,您使用entity.NavigationProperty.Id,不entity.NavigationPropertyId =>你還是不知道,如果實體有一個不爲空NavigationProperty:它看起來像它沒有=>沒有惰性加載可以做的東西是零...

我想這是示例代碼,但我會去(當然,這將是更容易使用24直接在第二個查詢,但你可能想要ch ECK如果有什麼東西存在Entities該值)

var entity = context.Entities.FirstOrDefault(x => x.NavigationProperty != null && x.NavigationProperty.Id == 24); 

if (entity != null) { 
var otherEntity = context 
        .OtherEntities 
        .SingleOrDefault(x =>//Are your sure a FirstOrDefault is not enough ? 
         (x.NavigationPropertyId == entity.NavigationProperty.Id)); 
} 
+0

這是示例代碼,我只是想證明一點,就是在生產中發生了類似的事情。顯然它比這更復雜,但這說明了這一點。你的觀點「現在你設置了它的外鍵值???這不會影響最終的導航屬性,如果你不保存實體」可能是我正在尋找的答案。我會在此期間檢查實體是否已保存。 – Klaws86

+0

標記爲答案,因爲該實體尚未保存。感謝您指出了這一點。 – Klaws86