How flexible can my LINQ To SQL statements be?

.net-3.5 c# dynamic-linq linq-to-sql sql

Question

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)";
            }
1
5
5/14/2010 3:58:19 PM

Accepted Answer

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).

1
5/14/2010 4:17:00 PM

Popular Answer

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



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow