C#Linq语句连接两个表和多个列

时间:2016-08-23 19:11:33

标签: c# asp.net-mvc linq

我有两张桌子; EndToEnd和PartPort。我想从EndToEnd中的同一行获取PartPortA和PartportB数据,并使用它们查询Partport并从Partport获取它们可能位于Partport表中任何行的相应PartGid。到目前为止,我能够做到这一点,但我必须做两个不同的LINQ调用,但我想将它减少到一个。这是我的代码:

    // this demonstrates how to join two tables, however only works for one AssetportGid at a time
    var part_portGid_a_results = (from icp in entities.EndToEnd
                  where icp.IntertPortGidA != null &&
                  icp.IntertPortGidB != null
                  join ica in entities.PartPort
                  on icp.PartPortA   equals ica.PortGid
                  select new { icp.PartPortA, ica.PartGid, }).ToList();

    var part_portGid_b_results = (from icp in entities.EndToEnd
                                   where icp.IntertPortGidA != null &&
                                   icp.IntertPortGidB != null
                                   join ica in entities.PartPort
                                   on icp.PartPortB equals ica.PortGid
                                   select new { icp.PartPortA, ica.PartGid, }).ToList();



    return Json(part_portGid_a_results, JsonRequestBehavior.AllowGet);

我想做什么,而且我已经尝试但是出现了错误:

                var part_portGid_a_results = (from icp in entities.EndToEnd
                  where icp.IntertPortGidA != null &&
                  icp.IntertPortGidB != null
                  join ica in entities.PartPort
                  on icp.PartPortA && icp.PartPortB   equals ica.PortGid
                  select new { icp.PartPortA, ica.PartGid, }).ToList();

我得到的错误是:

Guid? EndToEnd.PartPortB

Error:
    Operator '&&' cannot be applied to operands of type 'System.Guid' and 'System.Guid?'

1 个答案:

答案 0 :(得分:2)

使用加入。如果你想加入一个复杂的"比较,只需制作笛卡尔积(from ... from)并用where子句链接行

var part_portGid_results = (from icp in entities.EndToEnd
                            where icp.IntertPortGidA != null &&
                            icp.IntertPortGidB != null
                            from ica in entities.PartPort
                            where icp.PartPortA == ica.PortGid
                               || icp.PartPortB == ica.PortGid
                            select new { icp.PartPortA, ica.PartGid, }).ToList();