你不能。数据读取器不会在其堆栈跟踪中进行通信。您可以做的是将数据读取器的使用包装在另一个类中。在我正在进行的一个项目中,我们为此使用了扩展方法。该类如下所示:
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);
}
}
您可以按如下方式使用它:
using (var reader = SqlHelper.ExecuteReader(...))
{
while (reader.Read())
{
yield return new Order()
{
OrderId = reader.GetInt32("orderId"),
ItemId = reader.GetInt32("itemId")
};
}
}
顺便提一句。这样的类还允许您取回Nullable<T>
对象并摆脱DbNull
您需要做的那些手动转换。