LINQ to Entity, using a SQL LIKE operator

Posted by Mario on Stack Overflow See other posts from Stack Overflow or by Mario
Published on 2010-03-22T15:58:09Z Indexed on 2010/03/22 16:01 UTC
Read the original article Hit count: 756

I have a LINQ to ENTITY query that pulls from a table, but I need to be able to create a "fuzzy" type search. So I need to add a where clause that searches by lastname IF they add the criteria in the search box (Textbox, CAN be blank --- in which case it pulls EVERYTHING).

Here is what I have so far:

    var query = from mem in context.Member
                orderby mem.LastName, mem.FirstName
                select new
                {
                    FirstName = mem.FirstName,
                    LastName = mem.LastName,

                };

That will pull everything out of the Member table that is in the Entity object.

Then I have an addition to the logic:

sLastName = formCollection["FuzzyLastName"].ToString();

if (!String.IsNullOrEmpty(sLastName))
   query = query.Where(ln => ln.LastName.Contains(sLastName));

The problem is when the search button is pressed, nothing is returned (0 results). I have run the query against the SQL Server that I expect to happen here and it returns 6 results.

This is the query I expect:

SELECT mem.LastName, mem.FirstName FROM Members mem WHERE mem.LastName = 'xxx'

(when xxx is entered into the textbox)

Anyone see anything wrong with this?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about entity-framework