【问题标题】:How to join 3 tables with linq如何使用 linq 连接 3 个表
【发布时间】:2017-01-30 10:48:28
【问题描述】:

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

查询应选择: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 限制为给定列表有困难。

【问题讨论】:

  • 这是一个糟糕的设计。在 entities 之间使用 relations 并让 ORM 做任何需要的连接。 SewagePlant 应该有一个 Company 属性。 Company 应该有一个 Duties 集合。加载单个Company 即可访问所有相关对象
  • 但在这种情况下,SewagePlant 有 n 家公司,而不是相反。
  • 所以也把它做成一个集合。只是不要滥用您的 ORM。创建正确的关系,不要像使用 SQL 一样尝试加入。

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


【解决方案1】:

你能尝试类似的东西吗?请加入部分

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 new
  {
      duty = s.Duty.Duty, 
      CatId = s.Company.CompanyName,
      SewagePlantName=s.SewagePlant.SewagePlantName
      // other assignments
  };

【讨论】:

  • 在第二次连接时我得到一个错误:-> 连接子句中的一个表达式的类型不正确。调用“加入”时类型推断失败。
【解决方案2】:
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
          };

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2018-11-07
    相关资源
    最近更新 更多