本文介绍了SQL数据读取器 - 处理空列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用一个SqlDataReader从数据库建立波苏斯。在code工作时,遇到在数据库中的空值除外。例如,如果在数据库中的名字列包含空值,则会引发异常。
I'm using a SQLdatareader to build POCOs from a database. The code works except when it encounters a null value in the database. For example, if the FirstName column in the database contains a null value, an exception is thrown.
employee.FirstName = sqlreader.GetString(indexFirstName);什么是在这种情况下,以处理空值的最佳方式?
What is the best way to handle null values in this situation?
推荐答案您需要检查 IsDBNull以便:
if(!SqlReader.IsDBNull(indexFirstName)) { employee.FirstName = sqlreader.GetString(indexFirstName); }这是你唯一的检测和处理这种情况可靠的方法。
That's your only reliable way to detect and handle this situation.
我包这些东西到扩展方法,而且往往返回默认值如果列确空:
I wrapped those things into extension methods and tend to return a default value if the column is indeed null:
public static string SafeGetString(this SqlDataReader reader, int colIndex) { if(!reader.IsDBNull(colIndex)) return reader.GetString(colIndex); return string.Empty; }现在你可以这样调用它:
Now you can call it like this:
employee.FirstName = SqlReader.SafeGetString(indexFirstName);,你就再也不必担心异常或空值。
更多推荐
SQL数据读取器
发布评论