LINQ 查询中没有结果给出 IF ELSE 语句中未设置对象实例的对象引用
我有以下代码:
DataClasses1DataContext db = new DataClasses1DataContext();
var UserInfo = db.Users.FirstOrDefault(u => u.Email == TextBox1.Text);
if (UserInfo.Email != null)
{
Label2.Text = "Email is not null";
}
else
{
Label2.Text = "Email is null";
}
如果表中存在电子邮件地址,它会成功打印“电子邮件不为空”。但是,如果没有匹配的记录,我会收到第 29 行的“对象引用未设置为对象实例”错误:
Line 27: DataClasses1DataContext db = new DataClasses1DataContext(); Line 28: Line 29: var UserInfo = db.Users.FirstOrDefault(u => u.Email == TextBox1.Text); Line 30: Line 31: if (UserInfo.Email != null)
我被难住了!任何帮助将不胜感激。
I have the following code:
DataClasses1DataContext db = new DataClasses1DataContext();
var UserInfo = db.Users.FirstOrDefault(u => u.Email == TextBox1.Text);
if (UserInfo.Email != null)
{
Label2.Text = "Email is not null";
}
else
{
Label2.Text = "Email is null";
}
If an e-mail address exists in the table, it successfully prints "Email is not null." However, if there is no matching record, I then receive an Object reference not set to an instance of an object error for Line 29:
Line 27: DataClasses1DataContext db = new DataClasses1DataContext(); Line 28: Line 29: var UserInfo = db.Users.FirstOrDefault(u => u.Email == TextBox1.Text); Line 30: Line 31: if (UserInfo.Email != null)
I'm stumped! Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可能想要检查谓词中是否为 null,但如果它是真正的数据库,则没有必要:
但更重要的是,第 31 行代码中存在明显错误。如果
FirstOrDefault
不存在'找不到匹配的对象,它不会返回所有字段设置为 null 的对象。它返回一个空引用——即根本没有对象。您需要对此进行测试:在我看来,您应该首先修复明显的错误,然后如果仍然遇到问题,则使用正确的代码更新您的问题。
You might want to check for null in the predicate, but if it's a real database it shouldn't be necessary:
But more importantly, there's an obvious error in your code on line 31. If
FirstOrDefault
doesn't find a matching object, it doesn't return an object with all fields set to null. It returns a null reference - i.e. no object at all. You need to test for that:In my opinion you should fix the obvious error first, then update your question with the correct code if you are still having problems.
仅当
db
或TextBox1
或TextBox1.Text
为 null 时,您才能在该行获得 null ref 异常。皆存疑。我认为你走错线了。You can only get a null ref exception on this line if
db
orTextBox1
orTextBox1.Text
is null. All are doubtful. I think you have the wrong line.试试这个:
Try this:
除此之外,你可以使用
Beside, you can use
首先,您必须检查 UserInfo 是否为空,然后尝试检查它的成员,如下所示:
它将解决您的问题。
first of all you have to check whether UserInfo is null then try to check it's members, like this:
It will solve your problem.
你也应该对“UserInfo”进行空检查....
尝试这个
if (UserInfo != null && UserInfo.Email != null)
you should also null check for "UserInfo" too....
try this
if (UserInfo != null && UserInfo.Email != null)