views:

165

answers:

4

Is it possible to create Linq Queries at runtime. Using an xml rule which can be translated to a Linq Query.

A: 

Yes. I'm not going to show you how to parse XML, but you can attach the Linq Extension methods like this:

var IQueryable<bla> query = myDataContext.BlahTable;  // I think you can also use IEnumerable.

if(/* something */)
{
    query = query.Where(b => b.Field1 > 0);
}

if(/* something else */)
{
    query = query.OrderBy(b => b.Field2);
}
John Gietzen
Adding to the above question, I require to build the Linq Queries parsing the xml rule at runtime also the query can be complex or simple based on the xml rule.
StevenzNPaul
+3  A: 

You can use Dynamic Linq.

Rik
A: 

Essentially you need to build an expression tree. There's a brief explanation here as an answer to another question about creating expression trees from XML.

FinnNk
+2  A: 

Ultimately, yes; but it isn't simple and you'll need to either:

  • learn the Expression API
  • use the pre-rolled dynamic LINQ library (from the samples download)

If you want to go the first option, then you need to create your own lambdas; imagine, for example, that you have something like (making things up here...):

<Filters>
    <Add Prop="Foo">My filter value</Add>
</Filters>

Then you would need to do something like:

XElement filters = ...; // the "Filters" element
IQueryable<Customer> query = ...; // your raw (unfiltered) query
foreach(var filter in filters.Elements("Add")) {
    var param = Expression.Parameter(typeof(Customer), "row");
    var body = Expression.Equal(
        Expression.PropertyOrField(param, (string)filter.Attribute("Prop")),
        Expression.Constant(filter.Value, typeof(string)));
    query = query.Where(Expression.Lambda<Func<Customer, bool>>(
        body, param));
}

The above (for each "Add" element) creates a lambda that filters the given member to the supplied value (assumes string, but you could of course do any conversions etc). All the other operations are availble, but this shows the minimal effect. Note that query becomes restricted through the loop.

Marc Gravell