簡體   English   中英

如何使用 linq 對 Entity Framework 中的列求和並將其與另一個表連接

[英]How sum a column in Entity Framework using linq and join it with another table

我有以下StockTransaction表。 特定品牌進出庫存的每一件東西都記錄在這張表中,所以我需要知道進入庫存的商品數量,反之亦然。

例如:10 件阿迪達斯品牌的 T 恤入庫,5 件售出,5 件 T 恤應保留庫存。

我想根據GoodsID列和Input列對Quantity列求和

在此處輸入圖像描述

我將它與GoodsBrand表一起加入。

注意: StockTransaction表和GoodsBrand表之間沒有關系。 我只想加入帶有GoodsBrandStockTransation以獲取其特定品牌的商品。

在此處輸入圖像描述

我想要這樣的東西:

在此處輸入圖像描述

任何解決方案?

提前致謝

說這可能是較短的版本有點模糊:

var result = transactions
    .Join(goodbBrands,
        tr => tr.GoodsID,
        gb => gb.GoodsID,
        ((transaction, brand) => new
        {
            transaction,
            brand
        }))
    .Join(goods,
        gbs => gbs.transaction.GoodsID,
        g => g.ID,
        (gbs, good) => new
        {
            Brand = gbs.brand,
            Transaction = gbs.transaction,
            Good = good
        })
    .Join(brands,
        gb => gb.Brand.BrandID,
        b => b.ID,
        ((gbs, brds) => new
        {
            Brand = brds,
            Good = gbs.Good,
            Transaction = gbs.Transaction
        })).Select(item => new
    {
        GoodsName = item.Good.Name,
        Brand = item.Brand.Name,
        Qty = item.Transaction.Quantity
    });

但實際上,使用 Entity Framework Navigation PropertiesInclude forLoading Related Data為表創建正確的 model 關系會好得多。

這樣上面的大規模查詢就可以變得簡單得多:

var res = transactions.Include(tr => brands)
    .Include(tr => goods)
    .Select( ... );

要選擇數量,您應該能夠:

firstTable.Where(x => x.Input).GroupBy(x => x.GoodsID).Select(x => x.Sum(y => y.Quantity));

我將把連接留作練習,因為它有據可查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM