0

I'm a bit confused here (undoubtedly due to being new to C# and entity framework but that's besides the point) I want to check for a situation where my query to the database returns no data and upon that happening set some values to variables on my page Below is the code I have up right now which is throwing an error telling me that I need to check for null on the very line where I am checking for null (if the UserName value is null the record was not returned as it is a required column). So what am I missing on how to go about checking for null return here?

using (CInTracDBEntities Context = new CInTracDBEntities())
{
var CInTracUsers = Context.CInTracUsers.Where(a => a.Login == HttpContext.Current.Request.LogonUserIdentity.Name).Select(x => new { x.Login, x.UserName, x.Status, x.StatusDate, x.ReviewDate }).FirstOrDefault();
if (CInTracUsers.UserName == null) 

Thanks, Ken....

Ken Carter
  • 355
  • 1
  • 15
  • 6
    Your `CInTracUsers.UserName == null` check will check to see if `UserName` is null, the problem you are having is that `CInTracUsers` is the thing that is null. Read the linked duplicate to learn the debugging skills on how to solve the problem. – Scott Chamberlain Jun 13 '16 at 15:39
  • Is it actually throwing an error, or is your IDE simply trying to tell you that `CInTracUsers` _may_ be null, which it will be if your `Where` fails to match anything. – James Thorpe Jun 13 '16 at 15:40
  • `null`-ness isn't transitive. `CInTracUsers` is `null`, so attempting to access it's `UserName` property is an exception. – Ian McLaird Jun 13 '16 at 15:40
  • 1
    change if `(CInTracUsers.UserName == null)` to `if (CInTracUsers != null && CInTracUsers.UserName == null)` – bto.rdz Jun 13 '16 at 15:41
  • You are correct. I just realized that I misread the question about which line the error was on. – Bradley Uffner Jun 13 '16 at 15:46
  • @bto.rdz I think you hit the nail on the head but further in my code I'm having similar issues when I go to assign return values to session variables. example: Session["CITLogin"] = CInTracUsers.Login; also wants me to check for null after going though the check on the return record earlier. Maybe I should start a new thread just for that..Whadya think? Ken... – Ken Carter Jun 13 '16 at 19:18
  • Would have to write each one something like this? if (CInTracUsers != null && CInTracUsers.Login != null) { Session["CITLogin"] = CInTracUsers.Login; } – Ken Carter Jun 13 '16 at 19:58

1 Answers1

0

ask for the whole object:

if (CInTracUsers == null) 

because if CInTracUsers is null you'll get an exception when calling any of his proprties

lem2802
  • 1,112
  • 7
  • 18