【问题标题】:How To Convert SQL command to Entity Framework and Lambda Expressions如何将 SQL 命令转换为实体框架和 Lambda 表达式
【发布时间】:2019-10-03 12:03:25
【问题描述】:

我想将一些 SQL 代码转换为实体框架

select *
into #invoice
from Invoice
where Track = 2

select Fuel.ID, SUM(ISNULL(#invoice.Price, 0)) as Price, SUM(ISNULL(#invoice.Price, 0))
from Fuel left outer join #invoice
on Fuel.ID = #invoice.Fuel
group by Fuel.ID

尝试编写此代码但结果为零 (0)(价格和升

var data = fules.GroupJoin(model,
          f => f.ID,
          m => m.ID,
           (f, m) => new { f, m })
         .SelectMany(x => x.m.DefaultIfEmpty(),
         (x, m) => new { Fuel = x.f, Price = m?.Price, Liter = m?.Liter })
          .GroupBy(A => A.Fuel)
          .Select(A => new { Fuel = A.Key.Name, Liter = A.Sum(B => B.Liter)
, Price = A.Sum(B => B.Price) })
              .ToList();

【问题讨论】:

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


    【解决方案1】:

    您不会将 SQL 转换为这样的 LINQ/Lambda 函数。而是从结果“grain”开始,然后按照导航属性填写投影列。

    类似:

    db.Feuls.Select( f => new 
       {
          Fuel = f.Name, 
          Liter = f.Invoices.Where( i => i.Track = 2 ).Sum( i => i.Liter ),
          Price = f.Invoices.Where( i => i.Track = 2 ).Sum( i => i.Price )
       });
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找这样的东西:

      var query = from f in db.Feuls
                  from i in f.Invoices.Where(x => x.Track == 2).DefaultIfEmpty()
                  group i by f.ID into g
                  select new
                  {
                     ID = g.Key,
                     Liter = g.Sum(x => g.Liter),
                     Price = g.Sum(x => g.Price)
                  };
      

      【讨论】:

      • 你能改变 lambda 语法吗?我不会这样使用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      相关资源
      最近更新 更多