【问题标题】:Converting a SQLServer to Linq Query将 SQL Server 转换为 Linq 查询
【发布时间】:2021-03-15 17:35:05
【问题描述】:

我想知道将此查询转换为 LINQ 的正确方法是什么。

SELECT  DISTINCT ( CONVERT(date,FechaCreacion)) FROM Tabla
where ID = 4
order by CONVERT(date,FechaCreacion) desc 
OFFSET     (0 * 20) ROWS    
FETCH NEXT 20 ROWS ONLY;

通过这个查询,它给我带来了这些数据:

 1. 2021-03-16
 2. 2021-03-15
 3. 2021-03-14
 4. 2021-03-13
 5. 2021-03-11
 6. 2021-03-09
 7. 2021-03-02
 8. 2021-02-28
 9. 2021-02-25
 10. 2021-02-24
 11. 2021-02-23
 12. 2021-02-22
 13. 2021-02-21
 14. 2021-02-19
 15. 2021-02-10
 16. 2020-11-30
 17. 2020-10-05
 18. 2020-02-18

LINQ:

var query = (from sp in esquema.Tabla
                                 where sp.ID== 4
                                 orderby DbFunctions.TruncateTime(sp.FechaCreacion) descending
                                 select new
                                 {
                                    fechacreacion = DbFunctions.TruncateTime(sp.FechaCreacion)
                                 }
                                 ).Skip(0* 20).Take(20).ToList().Distinct();  

与直接在 SQL Server 中进行的查询相比,使用 LINQ 给我带来的数据更少

 1. 2021-03-16
 2. 2021-03-15
 3. 2021-03-14
 4. 2021-03-13
 5. 2021-03-11
 6. 2021-03-09
 7. 2021-03-02
 8. 2021-02-28
 9. 2021-02-25
 10. 2021-02-24
 11. 2021-02-23

【问题讨论】:

  • 我投票结束这个问题,因为不是英语。
  • 这是一个英文网站。翻译或尝试es.stackoverflow.com
  • 如果我猜的话,我会说 SQL 中的 DISTINCT 子句比 Linq 中的子句执行(即在 20 行 OFFSET 之前)。跨度>

标签: c# .net sql-server linq


【解决方案1】:

您已将Distinct 应用于已分页的结果。这就是结果不同的原因。

var query = 
    from sp in esquema.Tabla
    where sp.ID == 4
    orderby DbFunctions.TruncateTime(sp.FechaCreacion) descending
    select new
    {
        fechacreacion = DbFunctions.TruncateTime(sp.FechaCreacion)
    };

var query = query
    .Distinct()
    .Skip(0 * 20)
    .Take(20)
    .ToList();

【讨论】:

    猜你喜欢
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2017-02-23
    相关资源
    最近更新 更多