int columnIndex = dataReader.GetOrdinal("field");
if (!dataReader.IsDBNull(columnIndex))
String myString = dataReader.GetString(columnIndex);
The idea being that GetOrdinal will fail with an IndexOutOfRangeException when I try to get a field that is not in the reader. I want this exception because it tells me quickly that there is a mismatch between my code and my DB.
Also GetOrdinal is much less brittle than hardcoding the ordinal itself as a magic number.
I typically use option 3. I like it because if the underlying query ever changes the column order it will still work, and it shows the name of what you're asking for right there rather than some magic number.
However, I use a lot of VB.Net, so the Convert.ToString() part can be done implicitly. C# types may have a different preference.
Also, there is a very small penalty for using field name rather than a column ordinal. I normally feel it's justified, but depending on your app you might want to take that into account.
发布评论
评论(3)
我总是这样做:
当我尝试获取不在读取器中的字段时,
GetOrdinal
将失败并出现IndexOutOfRangeException
。 我想要这个异常,因为它很快告诉我我的代码和数据库之间不匹配。此外,
GetOrdinal
比将序数本身硬编码为幻数要容易得多。I have always done it this way:
The idea being that
GetOrdinal
will fail with anIndexOutOfRangeException
when I try to get a field that is not in the reader. I want this exception because it tells me quickly that there is a mismatch between my code and my DB.Also
GetOrdinal
is much less brittle than hardcoding the ordinal itself as a magic number.我同意 Andrew Hare 的观点,此外,我已将功能封装在一个重载的扩展方法中,从而简化了操作:
无论如何,只是一次重构,对我帮助很大。
I agree with Andrew Hare, with the addition that I've enclosed the functionality in an overloaded extension method that simplifies the operation:
Anyway, just a refactoring that helped me tremendously.
我通常使用选项 3。我喜欢它,因为如果底层查询更改了列顺序,它仍然可以工作,并且它会显示您所要求的内容的名称,而不是一些神奇的数字。
不过,我经常使用 VB.Net,因此
Convert.ToString()
部分可以隐式完成。 C# 类型可能有不同的偏好。此外,使用字段名称而不是列序号的惩罚非常小。 我通常认为这是合理的,但根据您的应用程序,您可能需要考虑到这一点。
I typically use option 3. I like it because if the underlying query ever changes the column order it will still work, and it shows the name of what you're asking for right there rather than some magic number.
However, I use a lot of VB.Net, so the
Convert.ToString()
part can be done implicitly. C# types may have a different preference.Also, there is a very small penalty for using field name rather than a column ordinal. I normally feel it's justified, but depending on your app you might want to take that into account.