Linq Lambda和EF Lazy加载 - NullReferenceException

时间:2015-06-05 08:20:12

标签: c# linq entity-framework lambda

我有这个导致NullReferenceException的代码。我希望Lazy加载在评估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
            }

1 个答案:

答案 0 :(得分: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 =&gt;你仍然不知道实体是否有一个非null的NavigationProperty:看起来它没有=&gt;没有延迟加载可以在null的东西上完成...

我想这是示例代码,但我会选择(当然,在第二个查询中直接使用24要容易得多,但您可能想检查{{1}中是否存在某些内容使用此值)

Entities