Linq Lambda和EF延迟加载- NullReferenceException
本文关键字:NullReferenceException 延迟加载 EF Lambda Linq | 更新日期: 2023-09-27 17:53:54
我有这段导致NullReferenceException的代码。我希望延迟加载在lambda求值时启动,然后到数据库获取导航属性(最后一行)。我通过直接使用Id解决了这个问题,但我很好奇是否有人可以向我指出任何文档,解释这里发生的事情以及为什么这不起作用。
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
}
好吧,很多奇怪的事情
//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
会容易得多,但你可能想检查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));
}