使用Entity Framework加入四个表

时间:2017-10-19 14:56:45

标签: entity-framework join

我有4张桌子:

用户

  • USER_ID
  • 列表项
  • 的User_Name
  • COMPANY_ID
  • Depart_id
  • GROUP_ID

公司

  • COMPANY_ID
  • COMPANY_NAME

出发

  • Depart_id
  • Depart_Name

  • GROUP_ID
  • GROUP_NAME

我使用Entity Framework,如何获取用户信息:

  • USER_ID
  • 的User_Name
  • COMPANY_NAME
  • Depart_Name
  • GROUP_NAME

像这样:

var va = from vx in dbContex.User
         join vy in dbContext.Company
         on vx.CompanyId equals vy.Company_id                     
         into a
         from b in a
         select new {
              vx.User_id,
              vx.User_Name,
              CompanyName = b.Company_Name
         };

1 个答案:

答案 0 :(得分:0)

一种解决方案可能是:

var detailedUserInformations = (from u in dbContext.User
                                join c in dbContext.Company on u.Company_id equals c.Company_id
                                join d in dbContext.Depart on u.Depart_id equals d.Depart_id
                                join g in dbContext.Group on u.Group_id equals d.Group_id
                                select new
                                {
                                    UserId = u.User_id,
                                    UserName = u.User_Name
                                    CompanyName = c.Company_id,
                                    DepartName = d.Depart_Name,
                                    GroupName = g.Group_Name
                                }).ToArray();

在投射(.Distinct())您的选择之前,您必须检查.ToArray()是否有意义。