从SQL到Linq的方法MAX()

本文关键字:MAX 方法 SQL Linq | 更新日期: 2023-09-27 18:30:06

嗨,我正试图在Linq表达式中转换此SQL脚本

但我不知道Linq 中的MAX方法是如何实现的

有人能帮我吗?

谢谢!

SELECT c.Nome, 
       c.NumeroRG, 
       f.Tipo, 
       f.Descricao, 
       f.DataHora,
       f.IdCliente,
       c.IdCliente,
       f.IdFrequencia    
FROM Cliente c, Frequencia f
WHERE f.Tipo = 1
AND   c.IdCliente = f.IdCliente
AND   cast(f.DataHora as date) = cast(getdate() as date)
AND   f.IdFrequencia = (select MAX(fr.IdFrequencia) 
                        from frequencia fr 
                        where fr.IdCliente =c.IdCliente)

从SQL到Linq的方法MAX()

也许是这样的:

var query = from client in db.Cliente
            join freq in db.Frequencia
            on client.IdCliente equals freq.IdCliente
            where freq.Tipo == 1 
            && freq.DataHora.Date == DateTime.Now.Date
            && freq.IdFrequencia == db.Frequencia.Where(f => f.IdCliente == client.IdCliente)
                                                  Max(f => f.IdFrequencia)
            select new { .... };

如果您使用LINQ to Entities,可能需要将DateTime.Now.Date/DateTime.Today替换为SqlFunctions.DatePart,但您没有提到这一点。

效果很好!感谢

        var query = from client in db.Cliente
                    join freq in db.Frequencia
                    on client.IdCliente equals freq.IdCliente
                    where freq.Tipo == true
                    && freq.DataHora.Value.Date == DateTime.Today.Date
                    && freq.IdFrequencia == db.Frequencia.Where(f => f.IdCliente == client.IdCliente).Max(f => f.IdFrequencia)
                    select new { Nome = client.Nome, Descricao = freq.Descricao };