No result in a LINQ query gives a reference to an object not set to an object instance in an IF ELSE expression

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 email address exists in the table, it successfully prints "Email is not zero." However, if there is no corresponding entry, I get a link to an object that is 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 at a dead end! Any help would be greatly appreciated.

+3
6

, null , , :

var UserInfo = db.Users.FirstOrDefault(u => u != null &&
                                            u.Email == TextBox1.Text);

, 31. . FirstOrDefault , , null. , .. . :

if (UserInfo != null)
{
    Label2.Text = "User found";
}
else
{
    Label2.Text = "User not found";
}

-, , , .

+4
var UserInfo = db.Users.FirstOrDefault(u => u.Email == TextBox1.Text);

null ref , db TextBox1 TextBox1.Text null. . , .

+1

:

var UserInfo = db.Users.FirstOrDefault(u => !string.IsNullOrEmpty(u.Email) && u.Email == TextBox1.Text);
0

Alternatively, you can use

db.Users.Any(u=> u.Email!=null && u.Email == TextBox1.Text);
0
source
Check you code
var UserInfo = db.Users.FirstOrDefault(u => u.Email == TextBox1.Text);

if (UserInfo.Email != null) // it is wrong

First of all, you should check if UserInfo is null, then try checking it, for example:

if(UserInfo != null)
{
// your code
}

This will solve your problem.

0
source

you must also specify null for "UserInfo" ....

try it

if (UserInfo! = null && UserInfo.Email! = null)

        {
            Label2.Text = "Email is not null";
        }
        else
        {
            Label2.Text = "Email is null";
        }
0
source

Source: https://habr.com/ru/post/1732483/


All Articles