How to query first and last name in Entity Framework?

I want to have a pretty smart search box for finding objects by person's name. On linq it will 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 it looks like it might be a bad way to do things, and I'm really not sure how the performance degrades with Linq. Is this type of instruction accurate or is there a way to improve this?

+3


source to share


1 answer


EF is just going to convert the LINQ query to SQL and execute the SQL statement against the database. Your query above will translate into a where clause with OR. Each is contains()

converted like

to SQL. So you end up with something like:

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

      

As long as this final query works fine, you should be fine.



If it doesn't work well, you might want to look at adding an index, or maybe full text search.

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

+3


source







All Articles