In my search form I let the user specify which columns and what word to search for in that specific column.
What I get is a key-value mapping where key = column
and value = search words
. I loop through these keys and values and create a string (searchPhrase) that I want to use in my query. Something like:
var query =
db.Persons.
Where(searchPhrase);
But I don't know how to use my searchPhrase as a where condition?
Here's how I loop through my form collection
public ActionResult Search(FormCollection collection)
{
List<string> conditions = new List<string>();
for (int i = 1; i <= 4; i++)
{
if (!String.IsNullOrEmpty(collection["columnName" + i]))
{
string s = String.Empty;
s += collection["Attributes" + i].ToString();
s += " = '";
s += collection["searchWord" + i].ToString();
s += "'";
conditions.Add(s);
}
}
searchPhrase = string.Join(" AND ", conditions.ToArray());
}
I then want to use the searchPhrase in the above query which might look like
surname LIKE 'adam' AND surname LIKE 'bob'
This is the only way I can think of since I'm letting the user specify the columns.
EDIT
Here's the search form: (Btw, this is an admin feature so I'm not too worried about sql injection attacks)You should have a look at Dynamic LINQ.
精彩评论