使用LINQ INNER JOIN 3数据表

时间:2017-07-12 15:43:57

标签: c# mysql sql-server postgresql linq

尝试使用LINQ连接三个数据表table1,table2,table3。表1和表2在2条件下连接,表1和表3在1条件下连接。以下是我的代码。但我得到一个例外说 “无法将'System.DBNull'类型的对象强制转换为'System.String'。”

以下是我的代码:

var result = from cust in tblCust.AsEnumerable()
             join mat in tblMat.AsEnumerable()
             new { coil_id = (string)cust["coil_id"], order_id = (string)cust["order_id"] }
             equals
             new { coil_id = (string)mat["PIECE_ID"], order_id = (string)mat["PRODUCTION_ORDER_ID"] }
                                 join parts in tblParts.AsEnumerable() on (string)mat["PIECE_ID"] equals (string)parts["ProdCoilNo"]
             select new
             {
                 coil_id = mat["PIECE_ID"],
                 order_id = mat["PRODUCTION_ORDER_ID"],
                 part = parts["PartNumber"],
                 gauge = mat["THICKNESS"],
                 width = mat["WIDTH"],
                 weight = mat["WEIGHT"],
                 code = mat["MATERIAL_BLOCK_STATE"],
                 requestor_comment = cust["requestor_comment"],
                 requestor = cust["requestor"],
                 updated_by_comment = cust["updated_by_comment"],
                 updated_by_user = cust["updated_by_user"]                                     
             };

我在(字符串)部分[“ProdCoilNo”]

附近得到一个例外

2 个答案:

答案 0 :(得分:0)

对包含null的字段使用coalesce运算符替换为空字符串

像这样:

coil_id = mat["PIECE_ID"] ?? String.Empty,

答案 1 :(得分:0)

使用coalesce运算符

var result = from cust in tblCust.AsEnumerable()
         join mat in tblMat.AsEnumerable()
         new { coil_id = (string)cust["coil_id"], order_id = (string)cust["order_id"] }
         equals
         new { coil_id = (string)mat["PIECE_ID"], order_id = (string)mat["PRODUCTION_ORDER_ID"] }
                             join parts in tblParts.AsEnumerable() on (string)mat["PIECE_ID"] equals (string)parts["ProdCoilNo"]
         select new
         {
             coil_id = mat["PIECE_ID"]?? String.Empty,
             order_id = mat["PRODUCTION_ORDER_ID"]?? String.Empty,
             part = parts["PartNumber"]?? String.Empty,
             gauge = mat["THICKNESS"]?? String.Empty,
             width = mat["WIDTH"]?? String.Empty,
             weight = mat["WEIGHT"]?? String.Empty,
             code = mat["MATERIAL_BLOCK_STATE"]?? String.Empty,
             requestor_comment = cust["requestor_comment"]?? String.Empty,
             requestor = cust["requestor"]?? String.Empty,
             updated_by_comment = cust["updated_by_comment"]?? String.Empty,
             updated_by_user = cust["updated_by_user"]?? String.Empty                                     
         };