Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a default value for a field of a FileHelpers element class

I'm trying to load a CSV file (delims are ';' and quotes are '"').

I have successfully created everything (the wizard tool is awesome), but there's one thing that I can't find a solution for.

Basically, I have an integer (System.Int32) column. In theory most of the records will have a positive integer value in that column. Sometimes, however, I might encounter a value "N/A" in that column. What I want to achieve, is have FileHelpers assign a default value (-1 works just fine), when it encounters "N/A" in that column.

Does anyone know if this is possible?

PS: I might need to do the same for a System.DateTime field (it might also have "N/A" sometimes).

like image 266
Paulius Avatar asked Jan 05 '10 15:01

Paulius


1 Answers

The best way that comes to mind to do what you want would be to use the FieldConverter attribute on those fields and create custom converter classes that assign the default value you want the field to have.

You need to create a class that inherits ConverterBase, and then provide implementations for the two virtual methods, StringToField() and FieldToString().

In the FieldToString() method, you'll check to see if the string is equal to "N/A". If it is, return the default value you want.

You will need two different classes, one that can handle Int32 and one that can handle DateTime.

The FileHelpers documentation has an example of how to do this. Link

like image 102
Brandon Ording Avatar answered Nov 15 '22 00:11

Brandon Ording