【问题标题】:Convert the SQL Query in to Linq Query将 SQL 查询转换为 Linq 查询
【发布时间】:2019-09-13 18:44:24
【问题描述】:

我是 EF Core 框架的新手,正在努力学习它。我已尝试执行 SQL 查询并从数据库中获得响应,但现在尝试将以下 SQL 查询转换为 Linq 查询以将其与 EF Core 一起使用。我的 SQL 查询如下

public static string shipQuery = @"SELECT distinct newid() as  Id
                  ,[prj_number]
                  ,[ship_Date]
                  ,[delivery]
                  ,,CONVERT(VARCHAR(10),  [delDate], 110) as delDate
                  ,[po]
                  ,[so]      
                  ,SUM([qty_so]) as total_qty
                  FROM [sDev].[dbo].[PrjDetails] 
                  where [Rep_Prj] = @rep and [so_status] not in ('Canceled','Voided lines') 
                  group by Id,[prj_number],[ship_Date],[delivery],delDate,[po],[so]
                  ORDER BY ship_Date DESC";

我已经在我的 EF Core 框架中使用了这个 SQL 查询来获取类似的数据

_context.shipByRepo.FromSql<shipByRepo>(shipQueries.shipQuery, rep).ToList();

这按预期工作。为了即兴发挥我试图将查询转换为 Linq 查询的框架。 作为初步尝试,我刚刚过滤了rep

   _context.shipByRepo.Where(w => w.Reporting_Project == rep).ToList();

这行得通,但我不确定我该如何做上述事情,比如与 Group by 和 Orderby 一起进行日期转换和求和

在之前的 SQL 查询中,我将模型设置为

  public class shipByRepo : IshipByRepo
  {
    public Guid Id { get; set; }
    public string prj_number { get; set; }
    public string ship_Date { get; set; }
    public string delivery { get; set; }
    public string delDate { get; set; }
    public string po { get; set; }
    public string so { get; set; }
    public decimal? total_qty { get; set; }
  }

但是通过我更改的 Linq 查询,我修改了 Model 类,但不包括总数量/转换日期字段

  public class shipByRepo : IshipByRepo
  {
    public string prj_number { get; set; }
    public string ship_Date { get; set; }
    public string delivery { get; set; }
    public DateTime? delDate { get; set; }
    public string po { get; set; }
    public string so { get; set; }
  }

【问题讨论】:

  • 可以添加实体模型吗?
  • @Jota.Toledo 更新了模型类
  • 这里的gui值是多少?我不明白它怎么会有任何价值,因为它没有存储在数据库中,只是在选择值时生成。
  • 另外,由于您在每一行上生成一个唯一的 GUID,DISTINCT 什么都不做。
  • 也许我的SQL to LINQ Recipe 可以帮助您入门?

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


【解决方案1】:

我认为下面的代码可以帮助你

    _context.shipByRepo
    .Where(x => x.Rep_Prj == rep && !x.so_status.Contains("Canceled") 
    && !x.so_status.Contains("Voided lines"))
    .OrderByDescending(x => x.ship_Date).Distinct().ToList();

如果您想选择使用.Select(x=&gt; new { x.propertyName, x.anotherOne })的字段数

【讨论】:

    【解决方案2】:

    您可以使用OrderBy(OrderByDescending) 和GroupBy,如下所示:

    _context.shipByRepo.OrderByDescending(x=>x.ship_Date)
                       .GroupBy(x=>new { x.prj_number,x.ship_Date,x.delivery,x.so,x.po,x.delDate})
                       .ToList();
    

    【讨论】:

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