您的位置:首页 > 其它

使用表达式树动态构建Linq查询条件来实现单个实体动态查询

2011-06-13 17:12 656 查看
// 得到城市ID,合法的ID>0,其他的小于0
var cid = Convert.ToInt32(ddlCity.SelectedValue);
// 创建静态类型为ut_View的参数表达式
ParameterExpression c = Expression.Parameter(typeof(ut_View), "c");
// 建立静态的True的表达式,用于与操作

Expression condition = Expression.Constant(true);

if (cid > 0)
{
//如果是合法City

// 该表达式用于判断一个ut_View类的CityID属性的值是等于传入的cid
Expression con = Expression.Call(
Expression.Property(c, typeof(ut_View).GetProperty("CityID")),
typeof(Nullable<int>).GetMethod("Equals", new Type[] { typeof(Nullable<int>) }),
Expression.Constant(cid, typeof(object)));
// 进行与运算
condition = Expression.And(con, condition);
}
// 建立lambda表达式委托
Expression<Func<ut_View, bool>> end = Expression.Lambda<Func<ut_View, bool>>(condition, new ParameterExpression[] { c });
// 传入委托
var query = _I360UModelContext.ut_Views.Where(end);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: