LINQ Dynamic Queries

Is it possible to create Linq queries at run time. Using an xml rule that can be translated into a Linq query.

+3
source share
4 answers

Ultimately, yes; but it is not easy, and you need to either:

  • learn API Expression
  • use the pre-deployed LINQ dynamic library (from sample loading)

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

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

Then you will 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));
}

( "" ) , ( , , , ..). , . , query .

+4
+3

. , XML, Linq Extension :

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

. XML.

0

Source: https://habr.com/ru/post/1722208/


All Articles