views:

77

answers:

3

I have the need to construct a LINQ To SQL statement at runtime based on input from a user and I can't seem to figure out how to dynamically build the WHERE clause.

I have no problem with the following:

string Filters = "<value>FOO</value>";
Where("FormattedMessage.Contains(@0)",Filters)

But what I really need is to make the entire WHERE clause dynamic. This way I can add multiple conditions at runtime like this (rough idea):

 foreach (Filter filter in filterlist)
            {
                whereclause = whereclause + "&& formattedmessage.contains(filter)";
            }
+5  A: 

Take a look at Dynamic Linq. Here is a link to get you started:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Randy Minder
Erm, did you mean to make that a link rather than a code snippet
Ben Robinson
Thanks Randy, I've read the article and it has helped to get me to where I am right now. Is it possible that what I need to do is beyond the scope of dynamic LINQ?
mcass20
No, dynamic LINQ can do what you want.
Craig Stuntz
I must be missing something. Are you guys telling me that I should be able to dynamically add the entire WHERE clause and not just add a parameter to the WHERE clause?
mcass20
How many times is it necessary to say, "Yes, Dynamic LINQ can do that!"?
Craig Stuntz
Twice. Thanks Craig.
mcass20
+1  A: 

I don't know what data types are being used here, but why don't you try to use general query?

var query = context.Messages
    .AsQueryable();

foreach (Filter filter in filterlist)
{
    query = query
        .Where(m => m.Contains(filter));
}

this will concatenate all the conditions using AND (as is in your question).

Alex
A: 

You may also consider using the PredicateBuilder class. Using that will allow you to dynamically add AND/OR conditions to your tree. Refer to http://www.albahari.com/nutshell/predicatebuilder.aspx

Saurabh Kumar