0

I am trying to convert a Dataset to a List of Object.

Here is what I have tried:

List<FundPerformanceRecord> FundPerformanceRecordList 
                            = ds.Tables[0].AsEnumerable()
                                .Select(x => new FundPerformanceRecord
                                         {
                                             FundCode = x.Field<string>("FUND_CODE"),
                                             OneMonth = x.Field<decimal>("ROR1MTH"),
                                             ThreeMonth = x.Field<decimal>("ROR3MTH")                                     
                                         })                         
                                .ToList();

The class FundPerformanceRecord has the properties defined as Nullable Decimal.

    [DataMember]
    public string FundCode;

    [DataMember]
    public decimal? OneMonth;

    [DataMember]
    public decimal? ThreeMonth;

I am getting the following error message if any Cell value in the dataset has null value.

System error - Cannot cast DBNull.Value to type 'System.Decimal'. Please use a nullable type.

How can I resolve this issue ?

Bluemarble
  • 1,925
  • 4
  • 20
  • 35

2 Answers2

3

The Field method supports nullable types, you just have to use them::

....
 .Select(x => new FundPerformanceRecord
 {
     FundCode = x.Field<string>("FUND_CODE"),
     OneMonth = x.Field<decimal?>("ROR1MTH"),
     ThreeMonth = x.Field<decimal?>("ROR3MTH")                                     
 })   
....
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Your model is has fields that are nullable types decimal? but when accessing and casting from the DataTable you are using a decimal instead of decimal?.

Try using x.Field<decimal?> as below:

List<FundPerformanceRecord> FundPerformanceRecordList 
                            = ds.Tables[0].AsEnumerable()
                                .Select(x => new FundPerformanceRecord
                                         {
                                             FundCode = x.Field<string>("FUND_CODE"),
                                             OneMonth = x.Field<decimal?>("ROR1MTH"),
                                             ThreeMonth = x.Field<decimal?>("ROR3MTH")                                     
                                         })                         
                                .ToList();
Dan D
  • 2,493
  • 15
  • 23