2016-07-18 55 views
6

我正在嘗試執行2個左側連接。我已經測試了SQL服務器中的查詢,它的工作原理,但我無法在linq中重新創建查詢。從左側加入選擇時出現NullReferenceException

查詢:

select Master.InvoiceId,Consumer.ConsumerId,ConsumerCharge.ChargeId , Amount 
from Master 

left outer join Consumer on 
Master.InvoiceId=Consumer.InvoiceId 

left outer join ConsumerCharge on 
Consumer.ConsumerId = ConsumerCharge.ConsumerId and 
Consumer.InvoiceId = ConsumerCharge.InvoiceId and 
Master.InvoiceId = ConsumerCharge.InvoiceId 

order by InvoiceId 

在LINQ:

var query = from m in IM.GetMaster() 

      join co in CM.GetConsumers() 
      on m.InvoiceId equals co.InvoiceId into temp2 
      from co in temp2.DefaultIfEmpty() 

      join ch in CCM.GetCharge() 
      on new { co.InvoiceId, co.ConsumerId, } equals new { ch.InvoiceId, ch.ConsumerId } into temp 
      from ch in temp.DefaultIfEmpty() 

      orderby m.InvoiceId 
      select new 
      { 
       InvioceID = m.InvoiceId, 
       ConsumerID = co == null ? 0 : co.ConsumerId, 
       ChargeID = ch == null ? 0 : ch.ChargeId, 
       Amount = ch == null ? 0 : ch.Amount 
      }; 

我越來越

對象引用不設置到對象的實例。

在線on new { co.InvoiceId, co.ConsumerId, }。如果我刪除into temp2 from co in temp2.DefaultIfEmpty(),則會顯示但不顯示消費者ID的發票ID。我如何進行正確的左連接,其中涉及3張表格?

回答

3

具有left join意味着,如果在第二個表中沒有匹配的記錄,那麼所有這些值null(從正常join不同,它不會從返回左表中的記錄)。你可能具有co等號null該記錄,所以你必須檢查它

試試這個:

var query = from m in IM.GetMaster() 

     join co in CM.GetConsumers() 
     on m.InvoiceId equals co.InvoiceId into temp2 
     from co in temp2.DefaultIfEmpty() 

     join ch in CCM.GetCharge() 
     on new { co?.InvoiceId, co?.ConsumerId, } equals new { ch?.InvoiceId, ch?.ConsumerId } into temp 
     from ch in temp.DefaultIfEmpty() 

     orderby m.InvoiceId 
     select new 
     { 
      InvioceID = m.InvoiceId, 
      ConsumerID = co?.ConsumerId, 
      ChargeID = ch?.ChargeId, 
      Amount = ch?.Amount 
     }; 

也看到你select new

使用
+0

@onedaywhen - 我使用顯示的屬性創建了這些類。但是,你忘了在'等'中加入''.'到'ch'端 - 編輯:) –

+0

@Scar - 它解決了你的問題嗎? –

+0

它現在有效,謝謝! :) – Scar