2016-10-18 31 views
0

我試圖將Uint(i_Customer)轉換爲Nullable Int(i_Customer)ID,因爲一個接受空值而另一個ID不支持。 父表是Customer(i_Customer),子表是故障(i_customer)。兩者,我正在加入他們的EF查詢來獲得結果。但有一個nullreferenceexception was unhandled by user code例外,這是非常令人不安。我如何解決它?Ho在EF查詢中將Uint轉換爲Nullable Int

這裏是EF查詢:

if (servicelevel == 3) 
      { 
       result = (from s in res 
          join cInfo in custInfo on 
          s.fault.i_customer equals Convert.ToInt32((int?)cInfo.customers.i_Customer) 
          where (s.fault.resolved == null) || (s.tasks.assignedto == agent) 
          orderby s.fault.ispriority descending, s.fault.logtime ascending 
          select new ActiveFaultResult() 
          { Company_Name = cInfo.customers.Company_Name, 
            //replies = replies, 
            idFaults = s.fault.idFaults, 
            hashvalue = s.fault.hashvalue, 
            responsible = s.fault.responsible, 
            logtime = s.fault.logtime, 
            isinternal = s.fault.isinternal, 
            ispriority = s.fault.ispriority 

          }).ToList<ActiveFaultResult>(); 

       // var limitresult = result.Take(50); 
       return result; 
      } 
+0

爲什麼不定義你的i_Customer爲INT? ? – mybirthname

+0

@mybirthname,這是可能的定義它,並在EF查詢中使用它?如果是這樣,怎麼樣?請協助。 –

+0

Convert.ToInt32((int?)cInfo.customers.i_Customer)=>(int?)cInfo.customers.i_Customer –

回答

0

正常投會做

s.fault.i_customer equals (int?)cInfo.customers.i_Customer 

或者試試這個

s.fault.i_customer ?? 0 equals cInfo.customers.i_Customer 
+1

那真是太棒了。我只是弄明白了:'將cust.infoUI中的cust.foUI轉換成convert.ToUInt32(f.i_customer?0),將cust.i_customer中的cust加入custo中​​,將custo.DefaultIfEmpty()'加入custo 。再次感謝 –

+0

@MichealP。很高興它有幫助 – Sherlock

+0

謝謝,我只是轉換了錯誤的ID。真的很感激先生! –

0

您需要使用DefaultIfEmpty()來提供外連接,以便它可以處理空值。見下面的例子:

result = (from s in res 
     join cInfo in custInfo on s.fault.i_customer equals (int)cInfo.customers.i_Customer into A 
     from cInfo in A.DefaultIfEmpty() 
     where (s.fault.resolved == null) || (s.tasks.assignedto == agent) 
     orderby s.fault.ispriority descending, s.fault.logtime ascending 
     select new ActiveFaultResult() 
     { 
       Company_Name = cInfo == null? String.Empty: cInfo.customers.Company_Name, 
       idFaults = s.fault.idFaults, 
       hashvalue = s.fault.hashvalue, 
       responsible = s.fault.responsible, 
       logtime = s.fault.logtime, 
       isinternal = s.fault.isinternal, 
       ispriority = s.fault.ispriority 
     }).ToList<ActiveFaultResult>(); 
return result; 
+0

謝謝,但我仍然得到相同的異常再次鑄造:'在custInfo中加入cInfo。 fault.i_customer等於(int)cInfo.customers.i_Customer從A.InfaultIfEmpty()中的cInfo到A ',你認爲它可能是什麼?請記住,我正試圖將uint32轉換爲Nullable Int,如(int?)。 –

+0

'(int。)cInfo.customers.i_Customer'這是Nullable Cast Exception的原因。有沒有錯誤可以通過它? –

+0

你可以檢查cInfo.customers本身是否爲null?您也可以嘗試從(int)cInfo.customers.i_Customer –