如何使用linq连接3个表

时间:2017-01-30 10:48:28

标签: c# asp.net-mvc entity-framework linq

我正在尝试在Linq的查询中加入3个表来从所有3个表中获取数据。下面是表格方案的图像:

enter image description here

查询应选择:SewagePlantName,CompanyName和Duty

此外,我需要将SewagePlantId限制为ID列表:

            var sewagePlantIds = UnitOfWork.GetAll<UserGroup>()
            .Where(group => group.Id == webAppPrincipal.GroupId)
            .SelectMany(group => group.SewagePlantId).Select(sewageplant => sewageplant.Id).ToList();

我在加入3个表格的顺序以及在何处/如何将SewagePlantId限制在给定列表时遇到了困难。

2 个答案:

答案 0 :(得分:9)

你可以尝试类似的东西加入

 from d in Duty
join c in Company on d.CompanyId equals c.id
join s in SewagePlant on c.SewagePlantId equals s.id
  .Select(m => new
  {
      duty = s.Duty.Duty, 
      CatId = s.Company.CompanyName,
      SewagePlantName=s.SewagePlant.SewagePlantName
      // other assignments
  });

答案 1 :(得分:0)

var obj = from trns in context.tblPartyRegistrations
          join st in context.tblSellingTrans
          on trns.PartyRegId equals st.Fk_PartyRegId
          join pt in context.tblPartyRemainings
          on trns.PartyRegId equals pt.fk_PartyId
          select new
          {
              trns.Name,
              trns.PhoneNo,
              trns.Address,
              st.RecivedAmount,
              st.Date,
              st.CustomerType,
              st.MilkRate,
              st.Mltr,
              st.Mkg,
              st.NtAmnt,
              st.RemaningAmount,
              pt.Remainingammount
          };