2

I am trying to parse a csv file using csv helper

this is my maping class

sealed class CSVFileDefinitionMapFinal : CsvClassMap<CSVFileDefinitionFinal>
{ 
    public CSVFileDefinitionMapFinal()
    {
        Map(m => m.FARM_ID).Name("FRM_ID");
    }
}

this is my item class

class CSVFileDefinitionFinal
{
    public int FARM_ID { get; set; }
}

the problem is that the FRM_ID in the csv may hav null. so when I do the mappign above, I have an exception that null can't be transfer to integer. I am asking about if there is a way to try and catch that and set the value to -10 when it is null.

the try and catch should be in the maping class, but I couldn't know what to do after catching the exception. in other words, i couldn't know how to set default value to the maping object

Josh Close
  • 22,935
  • 13
  • 92
  • 140
Anastasie Laurent
  • 877
  • 2
  • 14
  • 26

2 Answers2

4

You can make that property nullable and not-automatic:

class CSVFileDefinitionFinal
{
    private int _farmId;

    public int? FARM_ID
    {
        get { return _farmId; }
        set { _farmId = value == null ? -10 : value.Value; }
    }
}

Note that you need to define a private int _farmId member in that class.

Marcel N.
  • 13,726
  • 5
  • 47
  • 72
4

You can just add a default to the mapping.

Map(m => m.FARM_ID).Name("FRM_ID").Default( -10 );
Josh Close
  • 22,935
  • 13
  • 92
  • 140