IList对象创建中的System.InvalidCastException

时间:2014-05-13 18:01:53

标签: c# .net exception ilist

以下代码应该将DataTable转换为IList个对象。问题是,如果DataTable中存在空值,则会产生DBNull错误。

在为Deduction对象的属性赋值之前,有没有办法检查空值?

public IList<Deduction> PrepareDeductions() //Entry point
{
    return GetDeductionsToList();
}


public IList<Deduction > GetDeductionsToList()
{
    return CalculateDeductions().Rows.OfType<DataRow>().Select(CreateDeductions).ToList();
}

private DataTable CalculateDeductions()
{
    return _DataService.GetDeductions();
}

private static Deduction CreateDeductions(DataRow row)
{
    return new Deduction()
    {
        EmployeeID = Convert.ToInt32(row[0]),
        EPFAmount = Convert.ToDecimal(row[2]),
        AdvanceAmount = Convert.ToDecimal(row[3]),
        MealsAmount = Convert.ToDecimal(row[4]),
        LoanInstalmentAmount = Convert.ToDecimal(row[5]),
        UniformInstalmentAmount = Convert.ToDecimal(row[6]),
        InsuranceInstalmentAmount = Convert.ToDecimal(row[7]),
        FineAmount = Convert.ToDecimal(row[8]),
        DeathDonationAmount = Convert.ToDecimal(row[9]),
        WelfareAmount = Convert.ToDecimal(row[10]),
    };
}

4 个答案:

答案 0 :(得分:2)

您可以使用IsNull检查null;见http://msdn.microsoft.com/en-us/library/chk182xa.aspx

答案 1 :(得分:2)

private static Deduction CreateDeductions(DataRow row)
{
    return new Deduction()
    {
        EmployeeID = row[0] == DBNull.Value ? 0 : Convert.ToInt32(row[0]),
        EPFAmount = row[2] == DBNull.Value ? 0 : Convert.ToDecimal(row[2]),
        AdvanceAmount = row[3] == DBNull.Value ? 0 : Convert.ToDecimal(row[3]),
        MealsAmount = row[4] == DBNull.Value ? 0 : Convert.ToDecimal(row[4]),
        LoanInstalmentAmount = row[5] == DBNull.Value ? 0 : Convert.ToDecimal(row[5]),
        UniformInstalmentAmount = row[6] == DBNull.Value ? 0 : Convert.ToDecimal(row[6]),
        InsuranceInstalmentAmount = row[7] == DBNull.Value ? 0 : Convert.ToDecimal(row[7]),
        FineAmount = row[8] == DBNull.Value ? 0 : Convert.ToDecimal(row[8]),
        DeathDonationAmount = row[9] == DBNull.Value ? 0 : Convert.ToDecimal(row[9]),
        WelfareAmount = row[10] == DBNull.Value ? 0 : Convert.ToDecimal(row[10]),
    };
}

答案 2 :(得分:0)

不确定,但您可以查看

if (row[0] != System.DBNull.Value))
{
    EmployeeID = Convert.ToInt32(row[0]);
}
else
{
 EmployeeID = somethingelse;
}

答案 3 :(得分:0)

您可以使用DataRow.Field扩展方法,该方法可以更好地支持数据库中的可空值,并且不会返回DBNull。您的属性应该可以为空 - 例如int?decimal?

EmployeeID = row.Field<int?>(0);
EPFAmount = row.Field<decimal?>(2);
etc.