How flexible can my LINQ To SQL statements be?

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

Question

I need to create a LINQ to SQL query based on input from a user at runtime, but I'm having trouble figuring out how to dynamically create the WHERE clause.

I don't object to the following:

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

But I really need the WHERE clause to be dynamic as a whole. In this manner, I may add a number of criteria during runtime, roughly as follows:

 foreach (Filter filter in filterlist)
            {
                whereclause = whereclause + "&& formattedmessage.contains(filter)";
            }
1
5
5/14/2010 3:58:19 PM

Accepted Answer

Why don't you try using a generic query? I have no idea what data types are being utilized here.

var query = context.Messages
    .AsQueryable();

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

utilizing AND, this will combine each condition (as is in your question).

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

Popular Answer

Utilizing the PredicateBuilder class is another option. You may dynamically add AND/OR criteria to your tree by using that. Please see 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