LINQ 到实体 - 空引用
我可以发誓这在前几天有效:
var resultSet =
(from o in _entities.Table1
where o.Table2.Table3.SomeColumn == SomeProperty
select o
).First();
SelectedItem = resultSet.Table2.SomeOtherColumn;
我在最后一行收到空引用异常:resultSet.Table2 为空。
我不仅确定所有外键等都具有正确的值,而且我不明白 Table2 怎么可能 为空,因为 o.Table2.Table3.SomeColumn == SomeProperty
。
resultSet 具有所有正确值,但 Table2 为空。
[编辑] 这有效:
SelectedItem = _entities.Table2.First(
o => o.Table2.SomeColumn == SomeProperty).SomeOtherColumn;
而且,上面的 resultSet
具有所有正确的值,因此这不是数据问题在数据库中; LINQ-to-entities 只是做错了事。
I could swear this was working the other day:
var resultSet =
(from o in _entities.Table1
where o.Table2.Table3.SomeColumn == SomeProperty
select o
).First();
SelectedItem = resultSet.Table2.SomeOtherColumn;
I am getting a null reference exception on the last line: resultSet.Table2 is null.
Not only am I sure that all the foreign keys and whatnot have the correct values, but I don't see how Table2 could be null, since o.Table2.Table3.SomeColumn == SomeProperty
.
resultSet has all the correct values, with the exception that Table2 is null.
[Edit] This works:
SelectedItem = _entities.Table2.First(
o => o.Table2.SomeColumn == SomeProperty).SomeOtherColumn;
And, above, resultSet
has all the correct values, so it is not a problem with the data in the database; LINQ-to-entities is simply doing something wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,它正在按设计工作。当您强制执行时,L2E 只会在表中
JOIN
。这提高了性能。只要你在L2E,你就可以引用任何关系。这就是它起作用的原因:此处的 lambda 表达式将由 LINQ to Entities 解释,并转换为 SQL。另一方面,这:
...给出
Table1
类型的结果。您现在处于对象空间中。由于您的查询不会强制加载Table2
,因此 L2E 不会为其生成 SQL 列。当您不需要Table2
时,这会导致更高效的 SQL。当你这样做时,你必须这样说:这会起作用。 但是,上面的
First(lambda)
方法是更好的解决方案。 (比较 SQL。)No, it's working as designed. L2E will only
JOIN
in tables when you force it to. This improves performance. As long as you are in L2E, you can reference any relationship. That's why this works:Your lambda expression here will be interpreted by LINQ to Entities, and converted to SQL. On the other hand, this:
...gives a result of type
Table1
. You are now in object space. Since your query does not forceTable2
to be loaded, L2E won't generate SQL columns for it. This results in more efficient SQL when you don't needTable2
. When you do, you have to say so:This will work. However, your
First(lambda)
method above is a better solution. (Compare the SQL.).首先可能不会返回任何东西。您确定数据集的 SomeColumn 中存在 SomeProperty 的值吗?
使用 .Any() 将整个内容包装在 if 中以确定是否有记录,或在 resultSet.Table2 上测试 null
.First may not be returning anything. Are you sure that the value of SomeProperty exists in SomeColumn on your dataset?
Wrap the whole thing in an if using .Any() to determine if you have a record, or test for null on the resultSet.Table2