SqlFunctions.DatePart equivalent in EF Core

.net-core entity-framework-core

Question

What is the equivalent of the following statement in EF Core?

SqlFunctions.DatePart("week", x.MyDate)

EF.Functions doesn't seem to have a DatePart method.

1
2
9/27/2018 4:27:49 AM

Popular Answer

for ef core 3.1 is little different solution, should cast argument first to SqlConstantExpression then pass its Value to SqlFragmentExpression constructor:

public static class DbFunctionExtensions
{
    public static int? DatePart(string type, DateTime? date) => throw new Exception();

    public static void ConfigureDbFunctions(this ModelBuilder modelBuilder)
    {
        var mi = typeof(DbFunctionExtensions).GetMethod(nameof(DatePart));

        modelBuilder.HasDbFunction(mi, b => b.HasTranslation(e =>
        {
            var ea = e.ToArray();
            var args = new[]
            {
                new SqlFragmentExpression((ea[0] as SqlConstantExpression).Value.ToString()),
                ea[1]
            };
            return SqlFunctionExpression.Create(nameof(DatePart), args, typeof(int?), null);
        }));
    }
}
2
1/10/2020 7:00:29 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow