如何将sql查询传输到linq

6jjcrrmo  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(279)

我正在尝试将sql查询转换为linq语句:

SELECT f.BarcodeNumber,m.Name, f.Model, SUM(f.Quantity) as FoundedAssetsQty, ISNULL(a.Quantity,0) as AssetQty
  FROM [InventoryDB].[dbo].[FoundedAssets] f
  join [InventoryDB].[dbo].[PhisicalStockCheckSheets] p on p.ID = f.PhisicalStockCheckSheetId
  join [InventoryDB].[dbo].[Inventories] i on i.ID = p.InventoryId
  left join [InventoryDB].[dbo].[Assets] a on a.BarcodeNumber = f.BarcodeNumber
  join [InventoryDB].[dbo].[Manufacturers] m on m.ID = f.ManufacturerId
  where p.InventoryId = 10
  group by f.BarcodeNumber, a.Quantity, f.Model, m.Name

我不知道怎么做。我试过很多方法,但都失败了。有人能帮我吗?

qfe3c7zg

qfe3c7zg1#

我尝试使用linqer,但是当我配置连接时它失败了,所以我自己写linq指令。最后我找到了答案。我没有提到实体之间的关系,但这在这里并不重要。

var summary = _context.FoundedAssets.Include(f => f.Manufacturer).
                Include(f => f.Asset).
                Include(f => f.PhisicalStockCheckSheet).ThenInclude(f => f.Inventory).
                Where(f => f.PhisicalStockCheckSheet.Inventory.ID == id).
                Select(x => new InventorySummaryModel()
                {
                    BarcodeNumber = x.BarcodeNumber.Value,
                    ManufacturerName = x.Manufacturer.Name,
                    Model = x.Model,
                    AssetsQuantity = x.Asset.Quantity,
                    FoundedAssetQuantity = x.Quantity
                }).ToList();

            var groupedSummary = summary.GroupBy(x => x.BarcodeNumber).Select(x => new InventorySummaryModel()
            {
                BarcodeNumber = x.First().BarcodeNumber,
                ManufacturerName = x.First().ManufacturerName,
                Model = x.First().Model,
                FoundedAssetQuantity = x.Sum(a => a.FoundedAssetQuantity),
                AssetsQuantity = x.First().AssetsQuantity
            }).ToList();

可能存在任何更简单的方法,但这一个工作正常。

相关问题