你不能。數據讀取器不會在其堆棧跟蹤中進行通信。你可以做的是將數據閱讀器的使用包裝到另一個類中。在我正在開發的一個項目中,我們使用了擴展方法。這個類看起來是這樣的:
using (var reader = SqlHelper.ExecuteReader(...))
{
while (reader.Read())
{
yield return new Order()
{
OrderId = reader.GetInt32("orderId"),
ItemId = reader.GetInt32("itemId")
};
}
}
BTW:
public static class DataRecordExtensions
{
public static byte GetByte(this IDataRecord record, string name)
{
return Get<byte>(record, name);
}
public static short GetInt16(this IDataRecord record, string name)
{
return Get<short>(record, name);
}
public static int GetInt32(this IDataRecord record, string name)
{
return Get<int>(record, name);
}
private static T Get<T>(IDataRecord record, string name)
{
// When the column was not found, an IndexOutOfRangeException will be
// thrown. The message will contain the name argument.
object value = record[name];
try
{
return (T)value;
}
catch (InvalidCastException ex)
{
throw BuildMoreExpressiveException<T>(record, name, value, ex);
}
}
private static InvalidCastException BuildMoreExpressiveException<T>(
IDataRecord record, string name,
object value, InvalidCastException ex)
{
string exceptionMessage = string.Format(CultureInfo.InvariantCulture,
"Could not cast from {0} to {1}. Column name '{2}' of {3} " +
"could not be cast. {4}",
value == null ? "<null>" : value.GetType().Name,
typeof(T).Name, name, record.GetType().FullName, ex.Message);
return new InvalidCastException(exceptionMessage, ex);
}
}
您可以按如下方式使用它。這樣的課程還可讓您獲取Nullable<T>
對象並擺脫您需要執行的那些手動DbNull
轉換。
你可以粘貼堆棧跟蹤 – Midhat 2010-05-12 08:35:23