简体   繁体   中英

Entity Framework - joining multiple record to one record

I have one table that name is A that is master, another table that name is B is detail

In A and BI have below records:

A table:

Id    Name         Family
-------------------------
 1   Ebrahim      Golkhani
 2   Javad        Nasiri

in B table:

AId    FactorName       Value
------------------------
 1     BaseSalary       1000
 1     Tax              10
 1     Insurance        20
 2     BaseSalary       2000
 2     Tax              50
 2     Insurance        30

I want to retrieve data like this:

Name     Family     BaseSalary    Tax     Insurance ....
--------------------------------------------------------
Ebrahim  Golkhani   1000          10      20
Javad    Nasiri     2000          50      30

record in table b is dynamic, this means that factor name is not static.

I want to implement this in Entity Framework.

tableA.Join(TableB,x=>x.Aid,y=>y.Aid, (x,y) => new { name = x.name,family = x.family,
                        BaseSalary = y.Where(x.FactorName=="BaseSalary").First().Value,
                        Tax = y.Where(x.FactorName=="Tax").First().Value,
                        Insurance = y.Where(x.FactorName=="Insurance").First().Value
                        //.....
    }).ToList()

You can try this.

var results  =  from g in tab2.GroupBy(k => k.AId)
                join t1 in tab1 on g.Key equals t1.Id
                select new
                {
                    t1.Name,
                    t1.Family,
                    BaseSalary = g.SingleOrDefault(c=>c.FactorName.Equals("BaseSalary")).Value, 
                    Insurance = g.SingleOrDefault(c => c.FactorName.Equals("Insurance")).Value,
                    Tax = g.SingleOrDefault(c => c.FactorName.Equals("Tax")).Value,
                };

Please note , this is not validating nulls in your table, I'm leaving it to you to add those validations

Working Sample attached.

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