How dynamically can I make my LINQ To SQL statements?

I need to create a LINQ To SQL statement at run time based on user input, and I cannot figure out how to dynamically build a WHERE clause.

I have no problem with the following:

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

But I really need to make the whole WHERE clause dynamic. This way, I can add several conditions at runtime (rough idea):

 foreach (Filter filter in filterlist)
            {
                whereclause = whereclause + "&& formattedmessage.contains(filter)";
            }
+5
source share
3 answers

I don't know what data types are used here, but why aren't you trying to use a generic query?

var query = context.Messages
    .AsQueryable();

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

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

+1
source

You may also consider using the PredicateBuilder class. Using this, you can dynamically add AND / OR conditions to your tree. See http://www.albahari.com/nutshell/predicatebuilder.aspx

0
source

All Articles