Tevis
Tevis

Reputation: 739

How to query first and last name in Entity Framework?

I want to have a fairly intelligent search box for finding objects by a person's name. In linq, it would look something like this:

users = users.Where(m => m.FirstName.Contains(query) || m.LastName.Contains(query) || (m.FirstName + " " + m.LastName).Contains(query) || (m.LastName + " " + m.FirstName).Contains(query) || (m.LastName + ", " + m.FirstName).Contains(query));

But this seems like it might be a bad way to do things, and I'm really not sure how performance degrades with Linq. Is this type of statement fine or is there a way to improve on this?

Upvotes: 3

Views: 3272

Answers (1)

Trent
Trent

Reputation: 1381

EF is just going to convert the LINQ query to SQL and execute the SQL statement against the database. Your query above will translate to a where clause with an OR. Each contains() will translate to a like in SQL. So, you'll get something like:

select *
from users
where FirstName like '%query%'
or LastName like '%query%'

As long as that resulting query performs okay, you should be fine.

If it doesn't perform well, you could look at adding an index or maybe using a full-text search.

https://msdn.microsoft.com/en-us/library/ms142571.aspx

Upvotes: 3

Related Questions