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.
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);
}));
}
}