对象不能从构造函数中的DBNull转换为其他类型 [英] Object cannot be cast from DBNull to other types in constructor

查看:4008
本文介绍了对象不能从构造函数中的DBNull转换为其他类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在列表中添加一个CompanyDetails对象,因此我从数据库中获取数据,并将其加载到构造函数中。

I need to add into the list one object CompanyDetails, so I get data from my database, and load it into constructor.

result.Add(new CompanyDetails() { 
    Name = dr["name"].ToString(), 
    City = dr["city"].ToString(), 
    StreetName = dr["streetName"].ToString(), 
    StreetNr = Convert.ToInt32(dr["apartmentNr"]), 
    Tax = int.Parse(dr["TAX"].ToString() )});

StreetNr Tax 可以有null值。当我试图运行它,我得到的错误:

StreetNr and Tax can have null value. And when I'm trying to run it i get the error:


对象不能从DBNull转换为其他类型

Object cannot be cast from DBNull to other types

如何解决?我知道通常我应该检查tax或streetNr是否等于DBNull,但我不知道我该如何做到这种情况下。

How can I fix it? I know that normally I should check if tax or streetNr equals DBNull or not, but I don't know how I can do it in this case.

这是类CompanyDetails :

this is class CompanyDetails:

public class CompanyDetails
{
    public string Name { get; set; }
    public string City { get; set; }
    public string StreetName { get; set; }
    public int? StreetNr { get; set; }
    public int? Tax { get; set; }

}


推荐答案

Tax = dr["TAX"] == DBNull.Value ? 0 : (int)dr["TAX"]

这将检查 null ,如果是,则将 int 值设置为 0

That will check if it's null, if it is, it sets the int value to 0, otherwise it assigns the integer value.

将您的代码应用到您的代码:

Applying that to your code:

result.Add(new CompanyDetails() { 
    Name = dr["name"].ToString(), 
    City = dr["city"].ToString(), 
    StreetName = dr["streetName"].ToString(), 
    StreetNr = dr["apartmentNr"] == DBNull.Value ? 0 : (int)dr["apartmentNr"]
    Tax = dr["TAX"] == DBNull.Value ? 0 : (int)dr["TAX"]
    )});

编辑:

如果 StreetNr Tax 已经是类型 int? / code>而不是 0


In case StreetNr and Tax are already of type int?, then just assign null instead of 0.

result.Add(new CompanyDetails() { 
    Name = dr["name"].ToString(), 
    City = dr["city"].ToString(), 
    StreetName = dr["streetName"].ToString(), 
    StreetNr = dr["apartmentNr"] == DBNull.Value ? (int?)null : (int)dr["apartmentNr"]
    Tax = dr["TAX"] == DBNull.Value ? (int?)null : (int)dr["TAX"]
    )});

这篇关于对象不能从构造函数中的DBNull转换为其他类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆