silhouette hustler
silhouette hustler

Reputation: 1763

Check if string already exist in Table

I want to check if the email that user entered already exist in Office table,take a look bellow what I have done so far, the problem is that officeEmail is always true, even though the entered email doesn't exist it's never returning NULL.

public static bool IsOfficeEmail(string email)
{

    using (var data = Database)
    {
        data.ObjectTrackingEnabled = false;
        var officeEmail = data.Offices.Where(a => a.Active && a.Email.Equals(email));

        if (officeEmail != null)                
            return true;
    }

    return false;
}

Upvotes: 1

Views: 101

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37050

Alternativly if you really want to use .Where you can also check if the returned collection contains ANY elements:

if (officeMail.Any()) // ...

Or even shorter:

if (officeMail.Any(a => a.Active && a.Email.Equals(email))) // ...

If you want to ensure that there is exactly ONE item within your list matching your condition use .Single instead of .Any which will throw an exception if none or more then one item was found.

The actual reason for your check allways returning true is that .Where will return an enumerator even when no item matches the condition. Therefor the result is never null.

Upvotes: 2

Kamil Budziewski
Kamil Budziewski

Reputation: 23107

Where will not return you null, but empty sequence, change it to:

var officeEmail = data.Offices.FirstOrDefault(a => a.Active && a.Email.Equals(email));

if (officeEmail != null)                
    return true;

FirstOrDefault will return default value (here null) it will not find queried value.

It is an option to use Any if you are not interested in email record:

public static bool IsOfficeEmail(string email)
{
    using (var data = Database)
    {
        return data.Offices.Any(a => a.Active && a.Email.Equals(email))
    }
}

You will not get email record if you will not use it anyway. Which approach you should use depends on what will you do with officeEmail, if you are just querying if it exists -> Any will be the best approach here. If you would like to get check for existing record and do something with it, FirstOrDefault will be better.

Upvotes: 3

Related Questions