如何使用外部变量创建动态Labda表达式?

时间:2016-04-20 10:04:26

标签: c# linq lambda expression

我有一个场景,我有两个表'side'和'item'。

我正在尝试创建以下查询:

_db.SideTable.Where(s => s.Active && !_db.ItemTable.Any(i => i.SIDE_1 == s.ID));

但是SIDE_1实际上是动态的(SIDE_1到SIDE_20),其中数字1-20来自变量'sideId'。

我尝试过创建以下内容:

// Access the parameter's SIDE_xxx property
ParameterExpression param = Expression.Parameter(typeof(ItemTable));
Expression property = Expression.Property(param, "SIDE_" + sideId);
// Access the outer variable's ID property
ParameterExpression var = Expression.Variable(typeof(SideTable), "s");
Expression property2 = Expression.Property(var, "ID");
// Make the ID property value int? since the SIDE_xxx property may be null and otherwise the expression will fail
var valExpr = Expression.Convert(property2, typeof(int?));
// The body of the expression is simply an equal check
Expression body = Expression.Equal(property, valExpr);
// Create the expression
var expression = Expression.Lambda<Func<Artikel, bool>>(body, param);
// Get the data
_db.SideTable.Where(s => s.Active && !_db.ItemTable.Any(expression)).ToList();

当我运行时,我受到以下例外的欢迎:

参数's'未绑定在指定的LINQ to Entities查询表达式

我想我没有使用正确的语法来正确访问外部's'属性,但我不知道该怎么做。

0 个答案:

没有答案