简体   繁体   English

如何使用 linq 对 Entity Framework 中的列求和并将其与另一个表连接

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

I have the following StockTransaction table.我有以下StockTransaction表。 Every thing that come and goes into stock with a particular brand is recorded in this table so I need to know the amount of goods that entered the stock and vice versa.特定品牌进出库存的每一件东西都记录在这张表中,所以我需要知道进入库存的商品数量,反之亦然。

eg: 10 T-shirt with Adidas brand entered the stock and 5 sold therefor 5 T-shirt should be remain in stock.例如:10 件阿迪达斯品牌的 T 恤入库,5 件售出,5 件 T 恤应保留库存。

and I want to sum the Quantity column according to GoodsID column and Input column我想根据GoodsID列和Input列对Quantity列求和

在此处输入图像描述

And I join it with GoodsBrand table.我将它与GoodsBrand表一起加入。

Note: there is no relationship between StockTransaction table and GoodsBrand table.注意: StockTransaction表和GoodsBrand表之间没有关系。 I only want to join StockTransation with GoodsBrand to get goods with its particular brand.我只想加入带有GoodsBrandStockTransation以获取其特定品牌的商品。

在此处输入图像描述

I want something like this:我想要这样的东西:

在此处输入图像描述

Any solution?任何解决方案?

Thanks in advance提前致谢

It's kind of fuzzy to say that this can be the shorter version:说这可能是较短的版本有点模糊:

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
    });

but actually it would be much better to create correct model relations for the Tables using the Entity Framework Navigation Properties with the Include forLoading Related Data .但实际上,使用 Entity Framework Navigation PropertiesInclude forLoading Related Data为表创建正确的 model 关系会好得多。

This way the above massive query can become far simpler:这样上面的大规模查询就可以变得简单得多:

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

For selecting the quantity, you should be able to do:要选择数量,您应该能够:

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

I'll leave the join as an exercise, as it is well documented.我将把连接留作练习,因为它有据可查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM