【问题标题】:Convert this SQL query to LINQ using .GroupBy() methods使用 .GroupBy() 方法将此 SQL 查询转换为 LINQ
【发布时间】:2019-11-26 19:58:22
【问题描述】:

我在 SQL Server 中运行此查询:

SELECT 
    COUNT(SERIAL) AS [Cantidad de computadoras entregadas], 
    FechaEntrega AS [Fecha de Entrega]
FROM
    Inventary
WHERE  
    Modelo = 0 AND FechaEntrega > '2001-01-01 10:48:47.0000000' 
GROUP BY 
    FechaEntrega
ORDER BY 
    FechaEntrega

我尝试使用 C# 方法制作该表,但我不明白,显然,我误用了 GroupBy() 方法

<table>  
      <thead>
            <tr>
                <th>Fecha</th>
            </tr>
        </thead>
        <tbody>
            @foreach(
             var item in Model.Inventary 
                         .Where(m => m.Modelo == 0)
                         .Where(f  => f.FechaEntrega.Year > 2005)
                         .GroupBy( e => e.FechaEntrega)          
                    )
                   {
                     <tr>
                         <td>
                            @Html.DisplayNameFor(modelItem => item.FechaEntrega)
                        </td>
                     </tr>
                   }

          </tbody>
 </table>

【问题讨论】:

  • 也许我的SQL to LINQ Recipe 可以帮助你。请注意,您的 Razor 运行的查询与您的 SQL 不同(Count 在哪里?)

标签: sql-server entity-framework linq asp.net-core


【解决方案1】:

你的 sql 查询到 linq 的转换是这样的。您可以在控制器中执行此操作,然后将结果返回到视图
请看working fiddle

var model =  Inventary.Where(m => m.Modelo == 0)
                         .Where(f  => f.FechaEntrega.Year > 2005)
                         .GroupBy( e => e.FechaEntrega.Date)
                         .Select(p=> new YourCustomModelClass 
                          {
                              Fecha  =  p.Key,
                              Count  = p.Count()
                          });


public class YourCustomModelClass 
{
   public Datetime Fecha {set; get;}
   public int Count {set; get;}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多