I'm porting my site over from .NET Framework / MVC 5 / EF6 to .NET Core 3.1 MVC / EF Core. MSSQL Server for the database.
EF6 has SqlFunctions
of which one method is SquareRoot
, which translates to using SQRT
in sql queries against MSSQL Server.
EFCore does not have the SqlFunctions
class. It does have an equivalent DbFunctions
class but this is missing lots of methods.
After some googling about I've come up with the following for translating the LINQ query to sql:
MyDbFunctions.cs
public static class MyDbFunctions { public static double? SquareRoot(double? arg) => throw new Exception(); }
OnModelCreating method in DbContext
var sqrtMethodInfo = typeof(MyDbFunctions).GetMethod(nameof(MyDbFunctions.SquareRoot)); modelBuilder .HasDbFunction(sqrtMethodInfo) .HasTranslation(args => SqlFunctionExpression.Create("SQRT", args, typeof(double?), null));
Usage:
from a in context.Posts let sqrt = MyDbFunctions.SquareRoot(a.someColumnWithDoubleValue) where sqrt < 1337 select new MyViewModel { Sqrt = sqrt ... };
This seems to work nicely. I can see the use of SQRT
within the generated query (using SQL Server Profiler) and the where clause being applied. It also looks near identical to what EF6 generates.
I'm wondering if any EF Core pros can see anything wrong/pitfalls with the implementation (or improve on it)?
Math.Pow(a.someColumnWithDoubleValue, 0.5)
\$\endgroup\$Math
functions have mapper. Current translators, 5.0's translators. Related github issue\$\endgroup\$