【问题标题】:EF Core Implement sql server DATEPART as DbFunction static methodEF Core 将 sql server DATEPART 实现为 DbFunction 静态方法
【发布时间】:2018-12-26 22:44:27
【问题描述】:

我正在尝试将 DATEPART sql-server 函数添加到 Entity Framework Core,方法是将其作为静态方法添加到 DbContext 上,并使用此处所述的 [DbFunction] 属性https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0

问题是 sql-server 将 datepart 参数作为字符串接收,它无法运行它,因为 datepart 参数不能是字符串(基于https://docs.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?view=sql-server-2017“注意 DATEPART 不接受用户定义的变量等效项datepart 参数。”)

我还尝试通过执行 sting.Replace("\"", "") 从传递给 datepart 的参数中删除双引号,但它仍然不起作用(它从 "'arg'" 更改参数到'arg')

这是我的代码:

[DbFunction("DATEPART","")]
public static int DATEPART(string datepart, DateTime date)
{
    throw new NotSupportedException();
}

还有其他可以使用的数据类型吗?我错过了什么吗?

谢谢

【问题讨论】:

  • 我认为除了编写手动 SQL 之外,没有其他方法可以将该函数与 EF Core 一起使用。
  • 您可以定义一个包含 datepart 的 UDF,然后从您的代码中调用该 UDF。查询编译器应该内联函数调用,这样就不会对性能产生影响。
  • @Dai 您的意思是 sql-server 中的一个函数,该函数将调用 DATEPART,但我在代码中将调用我的自定义函数
  • 您为什么要这样做?代码会是什么样子。如果您尝试在 c# 之前更改值类型(datetime 为 int),那么您做错了地方。如果您尝试将其用于 where 子句,则您的架构是错误的。
  • @ErikPhilips 我在数据库中有两个表,我需要查询 tableA 在 tableB 的一周中的位置,这就是为什么我尝试使用 DATEPART wk,我无法将存储过程添加到数据库,我还有其他方法吗?谢谢? tnk

标签: c# linq entity-framework-core


【解决方案1】:

可以通过使用 DbFunctionAttribute 包装 datepart SQL 函数来使用它。 棘手的部分是告诉 ef core 不要将 datepart 类型参数作为字符串处理。示例:

数据库上下文:

public int? DatePart(string datePartArg, DateTime? date) => throw new Exception();

public void OnModelCreating(DbModelBuilder modelBuilder) {
    var methodInfo = typeof(DbContext).GetRuntimeMethod(nameof(DatePart), new[] { typeof(string), typeof(DateTime) });
    modelBuilder
        .HasDbFunction(methodInfo)
        .HasTranslation(args => new SqlFunctionExpression(nameof(DatePart), typeof(int?), new[]
                {
                        new SqlFragmentExpression(args.ToArray()[0].ToString()),
                        args.ToArray()[1]
                }));
}

查询:

repository.Where(x => dbContext.DatePart("weekday", x.CreatedAt) == DayOfWeek.Monday);

更多信息:https://github.com/aspnet/EntityFrameworkCore/issues/10404

【讨论】:

    猜你喜欢
    • 2019-10-09
    • 2020-05-12
    • 2020-07-01
    • 2019-12-04
    • 2022-10-13
    • 1970-01-01
    • 2021-11-24
    • 2022-01-30
    • 1970-01-01
    相关资源
    最近更新 更多