2012-03-29 46 views
3

我有以下表格:做2留在同一個表中加入一個電話

用戶:

  • 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(); 

和合並兩個,我相信那裏的列表必須是在一個查詢中同時執行這兩個操作的解決方案。

回答

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(); 
+0

儘管所有的答案的幫助下,這是一個最接近實際的解決方案:一個小小的改進:(c!= null)?c.carrierName:「」是需要的;而不僅僅是c.carrierName字段。感謝您的快速解答 – 2012-03-29 15:31:39

+0

沒問題。樂意效勞 :-) – Arion 2012-03-29 15:52:17

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();