通过一次调用在同一个表上执行2个左连接

时间:2012-03-29 14:50:27

标签: linq linq-to-sql

我有以下表格:

用户:

  • userIduserFirstNameuserLastName

holdBilling:

  • bEntityIDCarrierOIDPayerOIDholdTYPEcreateUserID

载体

  • carrierOIDcarrierName

付款人:

  • payerOIDpayerName

我希望代码保存在新实体中

holdBilling => new
{
      FirstName, LastName, CarrierName, PayerName
}

其中一个实体有付款人或承运人价值(不能兼得)。基本上我想通过一次调用在同一个表上进行2次左连接。这将是适用于我的SQL查询。

SELECT TOP 1000 [ID]
      ,[bEntityID]
      ,c.carrierID
      ,c.carrierName
      ,p.payerID
      ,p.payerName
      ,[holdType] ( this is "C" for carrier and "P" for payer ) 
  FROM .[dbo].[holdBilling] hb
  left join dbo.payer p on hb.payerID = p.payerID
  left join dbo.carrier c on hb.carrierID = c.carrierID
  where [bEntityID] = 378

我发现的临时解决方案是获取所有运营商的列表

 var listC = (from hold in holdBilling
              join u in Users on hold.createUserID equals u.userID
              join c in carrier.DefaultIfEmpty() on hold.carrierID equals c.carrierID
                             select new
                             {
                                 Elem = hold,
                                 FName = u.userFirstName,
                                 LName = u.userLastName,
                                 Carrier = c.carrierName,
                                 Payer = ""
                             }).ToList();

和所有付款人之一

 select new
        {
            Elem = hold,
            FName = u.userFirstName,
            LName = u.userLastName,
            Carrier = "",
            Payer = p.payerName
        }).ToList();

并合并两者,我相信必须有一个解决方案,可以在一个查询中同时进行。

2 个答案:

答案 0 :(得分:1)

您需要使用DefaultIfEmpty进行左连接

 var listC = (from hold in holdBilling
              from u in Users.Where(x => hold.createUserID == x.userID).DefaultIfEmpty()
              from c in carrier.Where(x => hold.carrierID == x.carrierID).DefaultIfEmpty()
              select new
              {
                Elem = hold,
                FName = u.userFirstName,
                LName = u.userLastName,
                Carrier = c.carrierName,
                Payer = ""
              }).ToList();

答案 1 :(得分:1)

这样的事情可能是:

var listC = (
                from hb in holdBilling
                from p in payer.Where(a=>a.payerID==hb.payerID).DefaultIfEmpty()
                from c in carrier.Where(a=>a.carrierID=hb.carrierID).DefaultIfEmpty()
                where hb.bEntityID==378
                select new
                {
                    hb.bEntityID,
                    c.carrierID,
                    c.carrierName,
                    p.payerID,
                    p.payerName,
                    holdType=(payer==null?"P":"C")
                }
                ).Take(1000)
                .ToList();