I have such tables in my database like Customer, Member, Instructor, Employee etc. Each of these users has his email adrress. I need to check if there is already a user with given email. I was thinking about:
- Check each table, something like this:
public bool IsEmailAddressExists(string email)
{
if (!Context.Customers.Any(c => string.Equals(c.Email, email, StringComparison.InvariantCultureIgnoreCase)))
if (!Context.Members.Any(m => string.Equals(m.Email, email, StringComparison.InvariantCultureIgnoreCase)))
...
}
- Select all emails and check:
public bool IsEmailAddressExists(string email)
{
var emails = Context.Customers.Select(c => c.Email).Union(Context.Members.Select(m => m.Email))...; //other unions
return emails.Any(e => string.Equals(e, email, StringComparison.InvariantCultureIgnoreCase));
}
There are more tables and many users, so I would like to know what would be the most efficient way to implement such kind of checking.
Thank you.
In pure SQL this would be your most efficient because it stops searching as soon as it hits a match:
… As a stored procedure:
… As a scalar-valued function:
In C# with Linq, you can use the Any extension and the || operator. Since Any usually gets translated to EXISTS in SQL and evalutation of the || operator in C# is lazy, evaluation will stop as soon as the first ocurrence of an email is reached.