views:

488

answers:

4

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.

A: 

Try this:

var UserInfo = db.Users.FirstOrDefault(u => !string.IsNullOrEmpty(u.Email) && u.Email == TextBox1.Text);
Geir-Tore Lindsve
+2  A: 

You might want to check for null in the predicate, but if it's a real database it shouldn't be necessary:

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

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:

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

In my opinion you should fix the obvious error first, then update your question with the correct code if you are still having problems.

Mark Byers
The exception should come on line 31 in that case
Geir-Tore Lindsve
A: 

Beside, you can use

db.Users.Any(u=> u.Email!=null && u.Email == TextBox1.Text);
Dennis Cheung
A: 
var UserInfo = db.Users.FirstOrDefault(u => u.Email == TextBox1.Text);

You can only get a null ref exception on this line if db or TextBox1 or TextBox1.Text is null. All are doubtful. I think you have the wrong line.

David B
What about if `db.Users` or `u` is null? Also `Textbox1.Text` being null shouldn't give an exception. The equality test should just return false.
Mark Byers
u never acquires a value (null or otherwise): it's just a lambda expression parameter that is used to generate an expression tree to generate some sql. db.Users is very unlikely to be null, but I suppose possible. You are right about Textbox1.Text
David B