【发布时间】:2020-08-04 05:55:37
【问题描述】:
我正在将一些代码从 asp.net 迁移到 asp.net 核心,但我找不到以字符串格式“yyyyMMdd”比较日期的方法,即 Datediff(day, column, "value" ) == x,数据库是 SQLServer,不能更改列类型。
我正在使用使事情复杂化的反射。
asp.net中的代码是
public static Expression ExpressionsDiffDate(Expression cte, Expression property)
{
MethodInfo DateDiff = typeof(SqlFunctions).GetMethod("DateDiff", new Type[] { typeof(string), typeof(string), typeof(string) });
if (property.Type == typeof(DateTime) || property.Type == typeof(DateTime?))
{
DateDiff = typeof(SqlFunctions).GetMethod("DateDiff", new Type[] { typeof(string), typeof(DateTime), typeof(DateTime) });
property = Expression.Convert(property, typeof(DateTime?));
cte = ConvertExpressionToDate(cte);
}
return Expression.Call(
DateDiff,
Expression.Constant("day"),
cte,
property
);
}
在这个例子中,我使用类 sqlfunctions 中的 datediff 方法,它有很多重载,取决于列类型,我使用将 datetime 作为参数的方法或使用字符串的方法。
我设法在 .net 核心中为 DateTime 类型的列做到了这一点
public static Expression ExpressionsDiffDate(Expression cte, Expression property)
{
ParameterExpression exFun = Expression.Parameter(typeof(DbFunctions));
MethodInfo DateDiff = typeof(SqlServerDbFunctionsExtensions).GetMethod("DateDiffDay", new Type[] { typeof(DbFunctions), typeof(DateTime), typeof(DateTime) });
return Expression.Call(
DateDiff,
exFun,
cte,
property
);
}
但我不知道如何对字符串类型的列执行此操作,因为它没有任何接受字符串的重载。
谢谢
【问题讨论】:
标签: c# sql-server asp.net-core entity-framework-core