csharp 左连接LinQ SQL

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 左连接LinQ SQL相关的知识,希望对你有一定的参考价值。

var query1 = from dailyStocktakeSettingLine in db.DailyStocktakeSettingLines
             where dailyStocktakeSettingLine.DailyStocktakeSettingID == dailyStocktakeSettingID
             select new {
                 ID = dailyStocktakeSettingLine.ID,
                 ProductID = dailyStocktakeSettingLine.ProductID
             };

var query2 = from stockMovement in db.StockMovements
             where stockMovement.CentreID == centreID && stockMovement.StockStateType == StockStateTypeEnum.Available
             group stockMovement by new { stockMovement.ProductID } into grp
             select new {
                 ProductID = grp.Key.ProductID,
                 Quantity = grp.Sum(e => e.Quantity)
             };

var query3 = from stockSnapshotLine in db.StockSnapshotLines
             join stockSnapshot in db.StockSnapshots on stockSnapshotLine.StockSnapshotID equals stockSnapshot.ID
             where stockSnapshot.CentreID == centreID && stockSnapshotLine.StockStateType == StockStateTypeEnum.Available
             group stockSnapshotLine by new { stockSnapshotLine.ProductID } into grp
             select new {
                 ProductID = grp.Key.ProductID,
                 Quantity = grp.Sum(e => e.Quantity)
             };

var query4 = from q1 in query1
             join q2 in query2 on q1.ProductID equals q2.ProductID into q1_q2
             from q2 in q1_q2.DefaultIfEmpty()
             join q3 in query3 on q1.ProductID equals q3.ProductID into q1_q3
             from q3 in q1_q3.DefaultIfEmpty()
             join product in db.Products on q1.ProductID equals product.ID
             join unit in db.Units on product.SmallUnitID equals unit.ID
             select new DailyStocktakeForAddLineData {
                 ID = q1.ID,
                 ProductID = product.ID,
                 ProductName = product.Name,
                 Quantity = (q2 == null ? 0 : q2.Quantity) + (q3 == null ? 0 : q3.Quantity),
                 SmallUnitName = unit.Name
             };

以上是关于csharp 左连接LinQ SQL的主要内容,如果未能解决你的问题,请参考以下文章

Linq 和 SQL的左连接右连接内链接

如何在 LINQ 中使用左外连接进行 SQL 查询?

SQL CE 上的 LINQ 聚合左连接

Linq to Sql:多个左外连接

将 SQL 转换为带有 null 的 Linq 左连接

Linq to Sql 左连接查询