问题
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