I am trying to find a user in my database, searching for email and phonenumber.
How ever, if I use a List or IEnumerable I’m getting a null refence exception. If I don’t use any of those, an “Not supported by SQL … ” is thrown.
My method:
public List<tblMember> getAllMembers()
{
return db.tblMembers.ToList();
}
private void confirmMembership(string email, int phoneNumber)
{
//var allMembers = db.tblMembers.AsEnumerable(); throws same exception
tblMember member = getAllMembers().FirstOrDefault(x => x.email.Equals(email, StringComparison.OrdinalIgnoreCase) && x.phoneNumber == phoneNumber); //This line throws exception, around email.Equals()
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
If I perform the search like this, no exception is thrown:
private void confirmMembership(string email, int phoneNumber)
{
//var allMembers = db.tblMembers.AsEnumerable(); throws same exception
tblMember member = getAllMembers().FirstOrDefault(x => x.email == email && x.phoneNumber == phoneNumber);
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
How can this be?
In the first case you are calling Equals() on an object that is null.
This throws an exception.
In the second case you are comparing two things one of which might be null
Here is the most current based on comments:
Here is another way that won’t throw an exception: