动态生成 LINQ 查询 [英] Dynamically generate LINQ queries

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

问题描述

我们有一个对象

public class SomeObject
{
   public Name {get;set;}
   public City {get;set;}
   public State {get;set}
   //various other parameters.  Let's say there's ~20
}

是否可以在不重新编译源代码的情况下动态创建新的 LINQ 查询?相反,查询参数来自在数据库中存储和更新的 XML 结构.

Is it possible to dynamically create new LINQ queries without recompilation of source code? Instead, the query parameters come from an XML structure that is stored and updated in the database.

var result = from i in someObj
             where 
             //XML requests Name = 'Bob'...so append this where clause
             name = 'Bob'

这能做到吗?

推荐答案

这是一个带有表达式树的解决方案:

Here is a solution with expression trees:

var param = Expression.Parameter(typeof(SomeObject), "p");
var exp = Expression.Lambda<Func<SomeObject, bool>>(
    Expression.Equal(
        Expression.Property(param, "Name"),
        Expression.Constant("Bob")
    ),
    param
);
var query = someObj.Where(exp);

我知道它要复杂得多,但这有时可能会有用.

I know it's much more complex, but this may be useful in times.

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

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