Search code examples
c#linq-to-entities

Linq to Entities query sum from 2 sums


Hello here's a sql query executed with linq to entities :

 private void GetDatas()
    {
        using(GSUITEEntities dc=new GSUITEEntities())
        {
            try
            {
                var query = from ent in dc.STOCK_ENT
                            join det in dc.STOCK_DET on ent.ENT_ID equals det.ENT_ID
                            join art in dc.FICHES_ARTICLES on ent.ART_CODE equals art.ART_CODE
                            join cli in dc.CLIENTS on ent.ENT_PROP equals cli.CLI_CODE
                            join seq in dc.MVTS_SEQUENCE on ent.ENT_ID equals seq.ENT_ID
                            join entr in dc.ENTREES_STOCKS on art.ART_CODE equals entr.ART_CODE                                
                            where seq.SEQ_STATUT != "V" && cli.CLI_CODE == "0030000"
                            && entr.ENTSTK_DATE_DEM == null
                            group new { ent, det, art, cli, seq, entr} by new
                            {
                                art.ART_CODE,
                                art.ART_LIBELLE1
                            } into grouped
                            let sumEntr=grouped.Sum(x=>x.det.DET_PNET)
                            where sumEntr<2000
                            orderby grouped.Key.ART_LIBELLE1
                            select new
                            {
                                code=grouped.Key.ART_CODE,
                                lib=grouped.Key.ART_LIBELLE1,
                                pnet=sumEntr,
                                pnetCong=grouped.Sum(x=>x.entr.ENTSTK_PNET)
                                // pnetTotal=pnet + pnetCong ; How to do that ??
                            };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }

And the last line is a comment. I would like had a calculated field to sum 2 grouped fields. pnet + pnetCong. How can this be possible ? Thank you for your help.


Solution

  • Why not just introduce another transparent identifier and use it?

    ...
    let sumEntr=grouped.Sum(x=>x.det.DET_PNET)
    let sumEntstkPnet=grouped.Sum(x=>x.entr.ENTSTK_PNET)
    where sumEntr<2000
    orderby grouped.Key.ART_LIBELLE1
    select new
    {
        code=grouped.Key.ART_CODE,
        lib=grouped.Key.ART_LIBELLE1,
        pnet=sumEntr,
        pnetCong=sumEntstkPnet
        pnetTotal=sumEntr+sumEntstkPnet
    };