简体   繁体   中英

'Object reference not set to an instance of an object.' in C# linq to SQL

this is the line of code where it shows the error

var physician = (from userAccounts in myDb.Physicians
                            where userAccounts.Phy_UserName == txtUserName.Text
                            select userAccounts).FirstOrDefault();

            setFirstName(physician.Phy_FName);

But in my setter I have a pre condition that if it's a null value it wouldn't do anything but how come it still shoes that error? here's my setters code

public void setFirstName(string fName) {
            if (fName == null)
            {
            }
            else {
                firstName = fName;
            }
        }

I'm guessing that your physician query returns null .

You're then attempting to call a property, Phy_FName , on a null value.

Checking for a null value in your setFirstName method will not protect you in this case, because Phy_FName isn't what's null , physician is.

As an aside, you may also want to check that fName isn't an empty string in your setFirstName method. You could check against both conditions by using if (!String.IsNullOrEmpty(fName))

Try this:

var physician = (from userAccounts in myDb.Physicians
                            where userAccounts.Phy_UserName == txtUserName.Text
                            select userAccounts).FirstOrDefault();

if(physician != null)
{
  setFirstName(physician.Phy_FName);
}
else
{
  //Throw Error or any any other processing as needed.
}

I bet physician is null. Are you sure you're getting anything back from the query?

The Phy_FName property will be evaluated either way so make sure physician isn't null before trying to read its properties.

You'll need to check the value of physician before attempting to use it:

if (physician != null)
    setFirstName(physician.Phy_FName);

To clarify on a wrong assumption of my own that maybe you were thinking also:

FirstOrDefault will return defaults if there is one, but the default for an object is null . So, most likely your Linq query is returning a null value for physician. Of which you are then trying to access the Phy_FName.

Here is a SO question that clarifies this more in depth: Specify default value for a reference type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM