views:

123

answers:

2

Hi, everybody!

Currently in our project we are using Entity Framework and LINQ. We want to create a search feature where the Client fills different filters but he isn't forced to.

To do this "dynamic" query in LINQ, we thought about using the Like operator, searching either for the field, or "%" to get everything if the user didn't fill that field.

The joke's on us when we discovered it didn't support Like. After some searching, we read several answers where it's sugested to use StartsWith, but it's useless for us.

Is the only solution using something like:

ObjectQuery<Contact> contacts = db.Contacts;
if (pattern != "")
{
      contacts = contacts.Where(“it.Name LIKE @pattern”);
      contacts.Parameters.Add(new ObjectParameter(“pattern”, pattern);
}

However, we'd like to stick with linq only.

Happy coding!

A: 

Reference System.Data.Linq.dll

using System.Data.Linq.SqlClient;

... .Where(it => SqlMethods.Like(it.Name, "pat%"));

Mark H
+1  A: 

Did you try using Contains?

contacts.Contains(pattern);

See this link for a succinct example of what LINQ generates.

http://davidhayden.com/blog/dave/archive/2007/11/23/LINQToSQLLIKEOperatorGeneratingLIKESQLServer.aspx

Abby Sims