score:14

Accepted answer

Try SquareRoot function defined in SqlFunctions

    var objects =
        from n in context.Products.Where(p => p.r == r)
        let a = SqlFunctions.SquareRoot((double)n.Latitude)
        where a < 5
        orderby a
        select n;

    return objects.Take(100).ToList();

score:1

Please try

var objects =
        from n in context.Products.Where(p => p.r == r)
        let a = Math.Pow((double)n.Latitude, 0.5)
        where a < 5
        orderby a
        select n;

score:5

If you start of learning LINQ with LINQ-to-objects, you'll run into this a lot once you start using LINQ-to-Entities.

You can do pretty much anything that will compile in LINQ-to-objects, because LINQ-to-objects translates into code when compiled.

LINQ-to-Entities (and LINQ-to-SQL) translates into expression trees. So, only the syntax that that specific LINQ provider allowed for is valid. In my first "for real" LINQ-to-Entities expression, which compiled just fine, I ran into this error about 5 times, as one by one I removed code that wasn't handled by LINQ-to-Entities.

So when you see this, it's normal and common. You need to find another way each time.

You could avoid the problem with a logical equivalent:

var objects =
    from n in context.Products.Where(p => p.r == r)
    where (double)n.Latitude < 25
    orderby a
    select n;

return objects.Take(100).ToList();

You could also pull all the data to the client and then run your code using LINQ-to-objects:

var objects =
    from n in context.Products.Where(p => p.r == r).ToList()
    let a = Math.Sqrt((double)n.Latitude)
    where a < 5
    orderby a
    select n;

return objects.Take(100).ToList();

Finally, you should be able to do this math on the server. Check out the System.Data.Objects.SqlClient.SqlFunctions SqlFunctions Class. These functions will translate into the expression. This in particular looks like it might be the ticket.


Related Articles