How to translate this SQL query to a LINQ query in EF Core?

后端 未结 2 1573
天涯浪人
天涯浪人 2021-01-21 11:28

I have the following table :

Indicators(A INT, B INT, C INT, D INT, TimeInsertedLocal DateTime) . 

And

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-21 11:45

    It's literally one to one translation.

    SQL query

    SELECT A, B, C, D , TimeInsertedLocal
    FROM Indicators
    WHERE TimeInsertedLocal >= 
    (   
        SELECT MAX(I.TimeInsertedLocal) 
        FROM Indicators AS I
    )
    

    EF Core LINQ query:

    var indicators = dbContext.Set();
    var query = indicators
        .Where(i => i.TimeInsertedLocal >= indicators.Max(i2 => (DateTime?)i2.TimeInsertedLocal));
    

    EF Core generated SQL query:

    SELECT [i].[A], [i].[B], [i].[C], [i].[D], [i].[TimeInsertedLocal]
    FROM [Indicators] AS [i]
    WHERE [i].[TimeInsertedLocal] >= (
        SELECT MAX([i2].[TimeInsertedLocal])
        FROM [Indicators] AS [i2]
    )
    

    The only specific detail in LINQ query is the DateTime? cast inside Max, otherwise EF Core will try to emulate LINQ Max method throwing behavior and will evaluate query client side.

提交回复
热议问题