Search code examples
c#.netexceptionilist

System.InvalidCastException in IList object creation


Following code is supposed to convert a DataTable to a IList of objects. The problem would be, if there is a null value in DataTable it'll generate an DBNull error.

Is there a way to check for nulls before assigning values to properties of Deduction object?

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]),
    };
}

Solution

  • 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]),
        };
    }