0

I have a LINQ query which I'm using to select some rows out of a SQL database. Each row from my database represents a footprint of physical space, and I'm trying to select just the rows which contain a given point. The part of the query that is giving me issues is below:

LinqMetaData meta = new LinqMetaData(da);

var captures = (from c in meta.Capture
                where

                (c.TLLat.HasValue && lat < Math.Max(Math.Max(c.BLLat.Value, c.BRLat.Value), Math.Max(c.TLLat.Value, c.TRLat.Value))) 
                &&
                (c.TLLat.HasValue && lat > Math.Min(Math.Min(c.BLLat.Value, c.BRLat.Value), Math.Min(c.TLLat.Value, c.TRLat.Value)))
                
                select c);

When I run the code, I get this error:

The binary expression '(39.3237282094724 < Max(Max(EntityField(LPLA_1.BLLat AS BLLat), EntityField(LPLA_1.BRLat AS BRLat)), Max(EntityField(LPLA_1.TLLat AS TLLat), EntityField(LPLA_1.TRLat AS TRLat))))' can't be converted to a predicate expression.

I've assumed this means I can't use Math.Max() / Math.Min() in a LINQ query...Is this correct?

EDIT:

I am using LinqMetaData for my query, which comes from the LLBLGen Pro c# library. I think that this implementation of LINQ may not support Math.Max() / Math.Min() within its queries.

dbc
  • 104,963
  • 20
  • 228
  • 340
Max
  • 808
  • 11
  • 25
  • 2
    It all depends on the underlying provider. You'd need to look into the documentation for it to find the appropriate methods that it can express. – asawyer Jul 20 '20 at 16:12
  • @asawyer I added some extra information to my question. But to what you're saying, I think the issue may be with the library I'm running my LINQ query through. – Max Jul 20 '20 at 16:29
  • 1
    Doesn't look like it: https://www.llblgen.com/documentation/5.3/LLBLGen%20Pro%20RTF/Using%20the%20generated%20code/Linq/gencode_linq_functionmappings.htm – asawyer Jul 20 '20 at 16:43
  • @asawyer Feel free to post as an answer and I'll give you credit -- you are correct – Max Jul 20 '20 at 17:03

1 Answers1

0

Simply move Max and Min calculations outside of your query as separate variables.
Not only that could affect your query overall performance but will remove the error you are seeing which is in this case connected to the provider unable to translate nested Max and Min methods.

Here is a Microsoft Documentation about some of the known issues with LINQ to Entities.

Another approach would be to convert the above query to pure SQL Procedure.

Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42