2014-10-31 65 views
1

表T1( 「P 01」)和T2( 「DTM」)包含以下值如何加入空值兩個表中引用的字段

Table t1 
PO101(string)  Loop_Id (Int) 
Item_1    6  
Item_2    8 
--- 
Table t2 
DTM02(string)  Loop_Id(int) 
20141029   (null) 
20141029   6 
20141101   8 

這個查詢

var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable() 
       join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable() 
       on t1.Field<string>("Loop_Id") equals t2.Field<string>("Loop_Id") 
       select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")}); 

失敗與

base {System.SystemException} = 
{"Cannot cast DBNull.Value to type 'System.Int32'. Please use a nullable type."} 

因爲t2.Loop_id中的空值。

如果我在t2中刪除包含空值的行,它工作正常。

如何將Loop_Id強制轉換爲可空或避免加入表中任何一個爲null的行?

回答

0
var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable() 
       join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable() 
       on t1.Field<string>("Loop_Id") 
       equals (t2.Field<string>("Loop_Id") == null 
        ? string.Emtpty : t2.Field<string>("Loop_Id")) 
       select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")}); 

我認爲它應該工作。請嘗試。

+0

木孔德,沒有同樣的事情.. – TonyP 2014-10-31 13:55:24

0

使用下面的查詢來處理null。

var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable() 
       join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable() 
       on t1.Field<int>("Loop_Id") equals t2.Field<int>("Loop_Id") 
       where t2.Field<int>("Loop_Id") != null 
       select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")}); 
+0

這現在用鹼失敗{System.SystemException} = {「無法轉換類型的對象 'System.Int32'輸入'System.String'。「} – TonyP 2014-10-31 13:45:27

+0

我已經更新查詢現在嘗試.. – user1089766 2014-10-31 13:51:42

+0

Nop,現在它拋出:{」不能投入DBNull.Value鍵入'System.Int32'。請使用可空類型。「} – TonyP 2014-10-31 13:54:35

1

下面是解

var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable() 
          join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable() on t1.Field<Nullable<int>>("Loop_Id") 
          equals (t2.Field<Nullable<int>>("Loop_Id")) 
          select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")} 
          ); 
+0

@paqoginez,它來自你的答案,謝謝。正如你所看到的那樣,靜態可空對象的使用消除了對where子句的需要。 – TonyP 2014-11-01 12:12:07

+0

@paqogomez,我沒有看到你的答案了! – TonyP 2014-11-01 15:50:16

+0

[在此處查找我的答案](http://stackoverflow.com/a/26658839/2589202) – paqogomez 2014-11-05 00:04:30

相關問題