I import records from csv files that do not have the same columns. I am trying to create a mapping that will see if a column is missing and then look into a different column and based on that create a value for the first one.
I tried something like this:
Map(m => m.ImportNo).TypeConverter<PeriodConverter>();
Map(m => m.Period).Optional();
And:
public class PeriodConverter : StringConverter
{
public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
{
if (String.IsNullOrWhiteSpace(text))
{
if (row.GetField("Period") == "08/2012 - 12/2012")
return 1;
else if (row.GetField("Period") == "01/2013 - 06/2013")
return 2;
else
return 0;
}
return int.Parse(text);
}
}
But it fails as there is no ImportNo column. On the other hand if i change the code of my mapping to this:
Map(m => m.ImportNo).Optional().TypeConverter<PeriodConverter>();
Map(m => m.Period).Optional();
By adding the Optional() It simply ignores the Type converter i have created. Is there a better way i could write this converter for it to work?
ConvertUsing
should work
Map(m => m.ImportNo).ConvertUsing(row =>
{
if(row.TryGetField("ImportNo", out int importNo))
{
return importNo;
}
if (row.GetField("Period") == "08/2012 - 12/2012")
return 1;
else if (row.GetField("Period") == "01/2013 - 06/2013")
return 2;
else
return 0;
});
Map(m => m.Period).Optional();