简体   繁体   中英

Dynamic LINQ Queries

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

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.

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);
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM