Dynamic LINQ Queries

坚强是说给别人听的谎言 提交于 2020-01-02 06:53:31

问题


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


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/1693526/dynamic-linq-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!