当数据存在时,LINQ 查询总是给出 nullref 异常

发布于 2024-11-16 10:29:07 字数 424 浏览 3 评论 0原文

我有以下查询,它们返回未设置为对象实例的对象引用错误:

    (From u In db.Customers Where u.CustomerEmail Like UserName.Text Select u.CustomerEmail).ToString
(From u In db.Customers Where u.CustomerEmail Like UserName.Text Select u).Single

如果我使用相同的值执行 sql 选择,我会得到所需的数据:

(select CustomerEmail from dbo.Customers where dbo.CustomerEmail like @UserName) 

请指出我的语法错误在哪里。

谢谢。

I have the following queries which are returning a Object reference not set to an instance of an object error:

    (From u In db.Customers Where u.CustomerEmail Like UserName.Text Select u.CustomerEmail).ToString
(From u In db.Customers Where u.CustomerEmail Like UserName.Text Select u).Single

If I do a sql select with the same values I get the required data:

(select CustomerEmail from dbo.Customers where dbo.CustomerEmail like @UserName) 

Please can you point out where I am going wrong with the syntax.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

未蓝澄海的烟 2024-11-23 10:29:07

如果您在查询后调用 ToList() 会发生什么。您看到预期的结果了吗?如果您不这样做并返回 null(这是不正确的,因为您期望空的 IEnumerable),这将解释该异常。

尝试从代码中消除使用的持久性框架,看看会发生什么。

What happens if you do a ToList() call after the query. Do you see the expected results? If you don't and get null back (which is incorrect as you would expect an empty IEnumerable) this would explain the exception.

Try to eliminate the used persistence framework from your code to see what happens.

演多会厌 2024-11-23 10:29:07

采用第一个语句

(From u In db.Customers Where u.CustomerEmail Like UserName.Text Select    u.CustomerEmail).ToString

这可能会给出空异常,

db is null

db.Customers is null

如果或,

UserName is null

并且我认为就是这样。

ToString 命令是否实际执行查询?我不知道 EntityFramework,但是如果像 Linq2Sql 一样,它返回 sql 查询,那么这不应该抛出 null 异常。如果它实际执行查询,则假设 u.CustomerEmail 被定义为字符串,那么我认为这不会抛出空异常。

如果这是丢失数据的情况,那么您仍然不会期望出现空异常。 Single 可能会抛出“序列不包含元素”错误。

Taking the first statement

(From u In db.Customers Where u.CustomerEmail Like UserName.Text Select    u.CustomerEmail).ToString

This can give a null exception if

db is null

db.Customers is null

or

UserName is null

and I think that's about it.

Does the ToString command actually execute the query? I don't know about EntityFramework, but if, like Linq2Sql, it returns the sql query, then this should not throw a null exception. If it actually executes the query, then assuming u.CustomerEmail is defined as a string, then again, I don't think this will ever throw a null exception.

If this was a case of missing data, then you would still not expect a null exception. Single might throw a 'Sequence contains no elements' error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文