【问题标题】:Converting SQL Query to LINQ for application将 SQL 查询转换为应用程序的 LINQ
【发布时间】:2014-04-29 12:52:38
【问题描述】:

我在 TSQL 中有一个查询,我正在尝试将其转换为 LINQ 以在我们的 Web 应用程序中使用,但我真的很努力解决这个问题。它是带有 EF6 的 MVC5,数据库是 SQL Server 2008 R2。任何帮助表示赞赏!

SQL 查询

select MAX(ShipFromCompanyName) as Supplier, COUNT(*) as AllSupplierCount, 
SUM(isnull(cast(TransportationCharges as decimal(18,2)),0)) as AllFreightCharges,
SUM(isnull(cast(TransportationCharges as decimal(18,2)),0)) * .45 as FreightSavings
from table
group by ShipFromCompanyName
order by ShipFromCompanyName

ShipFromCompanyNameTransportationCharges 都作为varchar 存储在数据库中,不幸的是我无法将TransportationCharge 的数据类型更改为小数

LINQ

var Scorecard = (from upsid in _db.table select upsid).GroupBy(x => new { x.ShipFromCompanyName, x.TransportationCharges })
            .Select(x => new
            {
                x.Key.ShipFromCompanyName,
                SupplierCount = x.Count(),
                FreightCharges = x.Key.TransportationCharges.Cast<decimal>().Sum(),
            }).ToList();

【问题讨论】:

  • 你试过decimal.Parse()吗?
  • 我会把它放在哪里?我要挂断的部分是普通 SQL 查询的 SUM()SUM() * .45 部分。
  • 您收到什么错误信息?

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


【解决方案1】:

我认为您需要进行后期处理,而不是让 SQL 来完成。让 SQL 尽可能多地做,然后在内存中做其余的事情

var Scorecard = (from upsid in _db.table select upsid).GroupBy(x => new { x.ShipFromCompanyName, x.TransportationCharges })
        .Select(x => new
        {
            x.Key.ShipFromCompanyName,
            SupplierCount = x.Count(),
            FreightCharges = x.Key.TransportationCharges,
        }).AsEnumerable()
        .Select (x => new 
        {
            ShipFromCompanyName = ShipFromCompanyName ,
            SupplierCount = SupplierCount ,
            FreightCharges = FreightCharges.Cast<decimal>.Sum() ,
        }

没有测试这段代码,但它应该给你的想法。

【讨论】:

    【解决方案2】:
    var Scorecard = (from upsid in _db.table select upsid)
    .GroupBy(x => new { x.ShipFromCompanyName, x.TransportationCharges })
    .Select(x => new
    {
        x.Key.ShipFromCompanyName,
        SupplierCount = x.Count(),
        FreightCharges = x.Key.TransportationCharges.Select(tc=>decimal.Parse(tc)).Sum()*0.45,
    }).ToList();
    

    由于我没有清楚地理解您的查询,我不确定,但这可能有效。

    【讨论】:

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