简体   繁体   English

实体框架-将多条记录连接到一条记录

[英]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 我有一个名称为A的表是主表,另一个名称为B的表是明细表

In A and BI have below records: 在A和BI中有以下记录:

A table: 一张桌子:

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

in B table: 在B表中:

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. 表b中的记录是动态的,这意味着因子名称不是静态的。

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 请注意 ,这不是验证表中的null,我留给您添加这些验证

Working Sample attached. 附有工作样品

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

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