我有這是導致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
}
在一行上你'entity.NavigationPropertyId =','後entity.NavigationProperty.Id',即'Id'成爲NavigationProperty'的'屬性第二種情況。這是錯誤還是問題的原因? –
顯然,'x'爲'null',或'entity.NavigationProperty'爲'null'。 –
Lasse,這不是重複的。我知道NullReferenceException是什麼。 X不能爲null,因爲它是lambda表達式的謂詞。 NavigationProperty顯然是空的,但我希望它是懶加載的,因此我的問題。 – Klaws86