我知道如何构建表达式树来查询实体框架,例如。
string propertyName = "Name";
string keyword = "Methanol";
ParameterExpression parameter = Expression.Parameter(typeof(Chemical), "x");
MemberExpression me = Expression.Property(parameter, propertyName);
ConstantExpression constant = Expression.Constant(keyword, typeof(string));
BinaryExpression body = Expression.Equal(me, constant);
var isEqualExpressionTree = Expression.Lambda<Func<Chemical, bool>>(body, new[] { parameter });
Expression<Func<Chemical, bool>> funcExpression = (Expression<Func<Chemical, bool>>)isEqualExpressionTree;
using (var mLEntities = new myLab02Entities1())
{
var cl = mLEntities.Chemicals.AsQueryable().Where(funcExpression).ToList();
return cl;
}
“名称”是SQL数据库中的一个字段,应检查“甲醇”。内置的Lambda是: {x =&gt; (x.Name ==“甲醇”)}。现在我想测试数据库的DateTime字段,但只测试Date-section。所以我的Lambda将是
{x =&gt; DbFunctions.TruncaateTime(x.EntryDate)== DbFunction.TruncateTime(testDate)}。这是按原样工作的,但是如何将其转换为表达式? 谢谢,哈基
答案 0 :(得分:0)
string propertyName = "EntryDate";
DateTime testDate = DateTime.Now;
ParameterExpression parameter = Expression.Parameter(typeof(Chemical), "x");
MemberExpression me = Expression.Property(parameter, propertyName);
var ce = Expression.Convert(me, typeof(DateTime?));
MethodCallExpression mc = Expression.Call(null, typeof(DbFunctions).GetMethod("TruncateTime", new Type[] { typeof(DateTime?) }), ce);
ConstantExpression constant = Expression.Constant(testDate, typeof(DateTime?));
BinaryExpression body = Expression.Equal(mc, constant);
var isEqualExpressionTree = Expression.Lambda<Func<Chemical, bool>>(body, new[] { parameter });
Expression<Func<Chemical, bool>> funcExpression = (Expression<Func<Chemical, bool>>)isEqualExpressionTree;