輕鬆玩轉 Typed DataSet, Part III Written by: Rickie Lee
Dec. 10, 2004
本文繼續前面《 輕鬆玩轉 Typed DataSet, Part II 》,這裡演練在使用 Typed DataSet 過程中,如何有效地 Debug 程序中出現的錯誤。最常見的錯誤 Exception 應該是:
An unhandled exception of type 'System.Data.ConstraintException' occurred in system.data.dll
Additional information: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
顯然,通過 VS.Net IDE 顯式的上述 Exception 信息,很難判斷到底錯誤在什麼地方。這裡提供的一個有效的方法來 Debug ,盡快找到 Bug 的真正原因,並加以解決。
private void PrintAllErrs(DataSet myDataSet)
{
DataRow[] rowsInError;
foreach(DataTable myTable in myDataSet.Tables)
{
// Test if the table has errors. If not, skip it.
if(myTable.HasErrors)
{
// Get an array of all rows with errors.
rowsInError = myTable.GetErrors();
Console.WriteLine(myTable.TableName + " " + rowsInError.Length.ToString()
+ " " + rowsInError[0].RowError);
// Print the error of each column in each row.
/*for(int i = 0; i< rowsInError.Length; i++)
{
foreach(DataColumn myCol in myTable.Columns)
{
Console.WriteLine(myCol.ColumnName + " " +
rowsInError[i].GetColumnError(myCol));
}
// Clear the row errors
rowsInError[i].ClearErrors();
}*/
}
}
}
通過上面的 PrintAllErrs() 方法,明確輸出錯誤的信息,其中註釋的 for 語句根據時間情況來確定是否需要。
下面演示如何使用上述 Code snippet ,下面的代碼與前面的 post 《 輕鬆玩轉 Typed DataSet, Part II 》相關,更詳細的信息,請參考《 輕鬆玩轉 Typed DataSet, Part II 》:
AnnotationTypedDataset theOrderDS = new AnnotationTypedDataset();
try
{
string strSelectOrders = "Select top 5 * From Orders ";
strSelectOrders += "Select * From [Order Details]";
SqlHelper.FillDataset(connStr, CommandType.Text, strSelectOrders, theOrderDS, new string[] {"Orders", "OrderDetails"});
StringBuilder strResults = new StringBuilder();
foreach(AnnotationTypedDataset.Order theOrder in theOrderDS.Orders)
{
strResults.Append(theOrder.OrderID.ToString() + " "
+ theOrder.CustomerID.ToString() + " "
+ theOrder.EmployeeID.ToString() + Environment.NewLine);
strResults.Append("Order Details: ");
strResults.Append(theOrder.GetChildRows("OrdertoOrderDetails").Length.ToString() + " ");
strResults.Append(theOrder.GetOrderDetails().Length.ToString());
strResults.Append(Environment.NewLine);
}
txtResults.Text = strResults.ToString();
}
catch
{
PrintAllErrs(theOrderDS);
}
異常 Exception 輸出結果:
OrderDetails 2141 ForeignKeyConstraint OrdertoOrderDetails requires the child key values (10253) to exist in the parent table.
包含有錯誤的 table name ,錯誤的 Rows 總數,並輸出第 1 行錯誤的具體信息,如果要輸出所有行的錯誤信息,則需要開發 PrintAllErrs() 方法的 for 循環。
通過上面輸出的錯誤信息,可以很快發現是上面的 SQL 語句有問題,子表 OrderDetails 的 key 值在父表 Orders 不存在。
Any questions or errors, please leave comments below. Thanks.
References:
1. Rickie, 輕鬆玩轉 Typed DataSet, Part I
2. Rickie, 輕鬆玩轉 Typed DataSet, Part II
3. MSDN, DataTable.GetErrors Method, http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDataDataTableClassGetErrorsTopic.asp