Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How dynamic can I make my LINQ To SQL Statements?

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)";
            }
like image 519
mcass20 Avatar asked Nov 15 '22 10:11

mcass20


1 Answers

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

like image 135
Oleks Avatar answered Dec 10 '22 03:12

Oleks