动态LINQ查询 [英] Dynamic LINQ Queries

查看:105
本文介绍了动态LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能创建LINQ查询在运行时。 使用XML规则,它可以转化为LINQ查询。

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:

  • 学前pression API
  • 使用pre-推出动态的LINQ库(从样品中下载)

如果你想要去的第一个选项,那么你需要创建自己的lambda表达式;想象一下,例如,你有什么样(胡编这里...):

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

以上(为每一个添加元素)创建一个lambda给定的成员用于过滤所提供的值(假设字符串,当然,你可以做任何转换等)。所有其他的操作都availble的,但是这示出了最小的影响。需要注意的是查询变为通过循环的限制。

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.

这篇关于动态LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆