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]),
};
}
System.InvalidCastException in IList object creation
Domanda
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]),
};
}
Soluzione
Altri suggerimenti
You can use IsNull
to check for null; see http://msdn.microsoft.com/en-us/library/chk182xa.aspx
Not sure but you can check like
if (row[0] != System.DBNull.Value))
{
EmployeeID = Convert.ToInt32(row[0]);
}
else
{
EmployeeID = somethingelse;
}
You could use the DataRow.Field
extension method, which has nicer support for nullable values in the DB, and doesn't return DBNull
. Your properties should be nullable - e.g. int?
, decimal?
.
EmployeeID = row.Field<int?>(0);
EPFAmount = row.Field<decimal?>(2);
etc.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow