【问题标题】:Comparing strings as dates using EF core 3使用 EF 核心 3 将字符串与日期进行比较
【发布时间】: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


    【解决方案1】:

    下面的“双重施法”技术

    (DateTime)(object)stringExpr
    

    (DateTime?)(object)stringExpr
    

    可用于欺骗 C# 编译器将string 类型表达式视为DateTime,从而允许您调用DateTimeDateTime? 重载DateDiff 方法(或使用DateTime 运算符)。

    用于 SqlServer 的 EF Core 查询翻译器将生成 CASTdatetimedatetime2 类型,这应该尝试从字符串进行默认 SqlServer 转换。

    例如像这样的

    if (property.Type == typeof(string))
        property = Expression.Convert(Expression.Convert(property, typeof(object)), typeof(DateTime));
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多