开发者

Query db with supplied where condition [duplicate]

开发者 https://www.devze.com 2023-03-11 00:29 出处:网络
This question already has answers here: Dynamic query with LINQ won't work (2 answers) Closed 3 years ago.
This question already has answers here: Dynamic query with LINQ won't work (2 answers) Closed 3 years ago. 开发者_运维问答

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)

Query db with supplied where condition [duplicate]


You should have a look at Dynamic LINQ.

0

精彩评论

暂无评论...
验证码 换一张
取 消