var searchDate = DateTime.ParseExact("17.12.2018", "dd.MM.yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
result = result.Where(DatePredicate("LaunchWeekStartDate", searchDate, 3));
我把这个表达式叫做
public static Expression<Func<General, bool>> DatePredicate(string columnName,
DateTime
searchValue,
int? operatorId)
{
var type = typeof(General);
var x = Expression.Parameter(type, "x");
var member = Expression.Property(x, columnName);
Expression expression;
var constant = Expression.Constant(searchValue, typeof(DateTime));
// Greater Than >
if (operatorId == 2)
{
expression = Expression.GreaterThan(member, constant); // THIS THROW ERROR
return Expression.Lambda<Func<General, bool>>(expression, x);
}
// Less Than <
else if (operatorId == 4)
{
expression = Expression.LessThan(member, constant); // THIS THROW ERROR
return Expression.Lambda<Func<General, bool>>(expression, x);
}
// Equal
var column = type.GetProperties().FirstOrDefault(p => p.Name == columnName);
expression = column == null
? expression = Expression.Constant(true) // THIS WORKS
: expression = Expression.Equal(member, constant); // THIS THROW ERROR
return Expression.Lambda<Func<General, bool>>(expression, x);
}
我得到的错误是
System.Data.SqlClient.SqlException(0x80131904):从字符串转换日期和/或时间时转换失败。
这很有效
var searchDate = DateTime.ParseExact("17.12.2018", "dd.MM.yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
result = result.Where(x => x.LaunchWeekStartDate == searchDate);
LaunchWeekStartDate的数据库列和类属性的类型为DateTime。
public class General
{
[Key]
public Int64 RowNumber {get; set;}
// ...
public DateTime LaunchWeekStartDate { get; set; }
}
请你解释一下这里的问题是什么?
而不是
Express.Equal
Express.Call
具有
CompareTo
var member = Expression.Property(x, columnName);
MethodInfo method = typeof(DateTime).GetMethod("CompareTo", new[] { typeof(DateTime) });
constant = Expression.Constant(searchValue, typeof(DateTime));
var call = Expression.Call(member, method, constant);
return Expression.Lambda<Func<General, bool>>(call, x);
System.ArgumentException:类型为“System.Int32”的表达式不能用于返回类型“System.Boolean”