Using SQRT in a Linq EF Query

I need to use the SQRT function as part of the where clause in a Linq EF query. I decided that I could do this:

var qry = context.MyTable.Where("sqrt(it.field) > 1");

But it returns an error saying that "sqrt" cannot be resolved into a valid constructor or function of the type., Next to the constructor of functions, methods or types, row 6, column 5. "

I always thought that linq literally takes what is in the where clause and translates it into a statement that runs directly in SQL. That doesn't seem to be the case ...

Does anyone know a workaround?

thanks

+3
source share
4 answers

I am using Linq Entities and was able to do this:

        testEntities entities = new testEntities ();

        ObjectQuery<Fees> fees = entities.Fees;

        return from f in fees 
               let s = Math.Sqrt((double)f.FeeAmount)
               where s > 1.0 
               select f ;

When I check the generated SQL, I get

SELECT [t1].[TestTriggerID]
FROM (
    SELECT [t0].[TestTriggerID], SQRT(CONVERT(Float,[t0].[TestTriggerID])) AS [value]
    FROM [TestTrigger2] AS [t0]
    ) AS [t1]
WHERE [t1].[value] > @p0

. .Where , , , .

+2

, EF. EF4, . :

LINQ to Entities Double Sqrt (Double) ', .

, ( , Math.Pow(double) , SQRT SQL), , , .

, .

from e in context.MyEntities
     let s = Math.Pow(e.MyDouble, 0.5)
     select s;

SQL POWER SQRT:

SELECT 
POWER( CAST( [Extent1].[MyDouble] AS float), cast(0.5 as float(53))) AS [C1]
FROM [dbo].[MyEntities] AS [Extent1]

. , - .

+8

Check msdn document . SQL code does not support sqrt function.

+1
source

You can use System.Data.Entity.SqlServer.SqlFunctions.SquareRootwith EF6.

0
source

Source: https://habr.com/ru/post/1720938/


All Articles