表t1(“PO1”)和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 :(得分: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")}
);
答案 1 :(得分: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")});
我认为它应该有效。请试试。
答案 2 :(得分: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")});