Dewald Henning
Dewald Henning

Reputation: 353

EDMX object reference not set to instance of an object

I've used this code multiple times in my web app and for some reason this part keeps returning the error: Object reference not set to an instance of an object.

string username = "John";

using (TicketsEntities dbc = new TicketsEntities())
                {
                    var usr = from cs in dbc.Logins
                              where cs.FullName == username
                              select cs;

                    DataModel.Login lgn = usr.SingleOrDefault<DataModel.Login>();
                    string user = lgn.Email;
                    lbler.Text = user;
                }

There is only one entry in my db both with the name "John". I have tested for null but it keeps giving me the error on string user = lgn.Email;

Upvotes: 4

Views: 1360

Answers (1)

Darren
Darren

Reputation: 70718

I assume that lgn is null, as usr maye have returned the default value null and assigned it to lgn. Therefore you can check that lgn is not null:

if (lgn != null && !string.IsNullOrWhiteSpace(lgn.Email) {
   user = lgn.Email;
}

user = "User not found/Email has not been set";

Upvotes: 2

Related Questions