我正在尝试从数据库执行存储过程。但是,我遇到了一个例外:
InvalidCastException:无法将“System.DBNull”类型的对象转换为
输入“System.Nullable`1[System.Int32]”。
“results.Add”行引发异常。
var result = new List<GetActiveUserPackagesForOpenBillingPeriodResult> ();
using (var conn = new NpgsqlConnection ("Host=localhost;Port=xxx;Database=xxx;Username=postgres;Password=xxx;TrustServerCertificate=true;ApplicationName=xxx;")) {
using (var cmd = new NpgsqlCommand ("\"GetActiveUserPackagesForOpenBillingPeriod\"", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue ("somedate", DateTime.Today);
conn.Open ();
var reader = cmd.ExecuteReader ();
string x = DBNull.Value.Equals (reader) ? " " : reader.ToString ();
if (x != null)
{
while (reader.Read ()) {
result.Add (
new GetActiveUserPackagesForOpenBillingPeriodResult {
Amount = (decimal) reader["Amount"],
AcceptanceActID = (int?) reader["AcceptanceActID"],
PackageID = (int) reader["PackageID"],
UserID = (int) reader["UserID"],
AccountID = (int) reader["AccountID"],
HasChangedPackage = (bool) reader["HasChangedPackage"],
}
);
}
}
}
}
From DBNull文档:
DBNull
代表一个不存在的值,其中null
表示不存在
对对象的引用。
要解决您的问题,
在更改值的类型之前检查 Null,然后将其分配给变量
result.Add (
new GetActiveUserPackagesForOpenBillingPeriodResult {
Amount = (decimal) reader["Amount"],
AcceptanceActID = Convert.IsDBNull(reader["AcceptanceActID"]) ? null : (int?) reader["AcceptanceActID"],
PackageID = (int) reader["PackageID"],
UserID = (int) reader["UserID"],
AccountID = (int) reader["AccountID"],
HasChangedPackage = (bool) reader["HasChangedPackage"],
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)