简体   繁体   中英

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

I have the following StockTransaction table. 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.

and I want to sum the Quantity column according to GoodsID column and Input column

在此处输入图像描述

And I join it with GoodsBrand table.

Note: there is no relationship between StockTransaction table and GoodsBrand table. I only want to join StockTransation with GoodsBrand to get goods with its particular brand.

在此处输入图像描述

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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