动态创建Expression调用方法EntityFunctions.DiffDays

时间:2010-10-19 15:10:02

标签: c# linq-to-entities lambda dynamic predicate

我正在尝试动态创建以下Where子句表达式:

context.Cars.
Where(c => EntityFunctions.DiffDays(c.Created, c.Created) == null).
ToList()

这是我用来创建表达式的代码:

var parameter = Expression.Parameter(typeof(Car), "c");
var property = Expression.Property(parameter, "Created");
var function = Expression.Call(typeof(EntityFunctions), "DiffDays", 
    null, property, property);
var comparison = Expression.Equal(function, Expression.Constant(null));
var result = Expression.Lamda<Func<Car, bool>>(comparison, parameter);

结果显示(似乎缺少“EntityFunctions.DiffDays”):

{c => (DiffDays(c.Created, c.Created) == null)}

当我尝试执行时:

context.Cars.Where(result.Compile()).ToList()

我收到错误消息:

  

此功能只能从中调用   linq to entities

你知道我错过了什么吗?是因为它只显示“DateDiff”而不是“EntityFunctions.DateDiff”

感谢。亚当

1 个答案:

答案 0 :(得分:2)

删除最后一行的“编译()”调用,如下所示:

context.Cars.Where(result).ToList();

并将编译推迟到LinqToEntities。