Question

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;

Was it helpful?

Solution

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";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top