4

我在我的网络应用程序中多次使用此代码,出于某种原因,这部分一直返回错误: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;
                }

我的数据库中只有一个名为“John”的条目。我已经测试了 null 但它一直给我错误string user = lgn.Email;

4

1 回答 1

2

我假设lgnnull,因为usrmaye 已返回默认值null并将其分配给lgn. 因此,您可以检查lgn不是null

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

user = "User not found/Email has not been set";
于 2013-09-05T14:37:21.673 回答