I have a record type, for example:
public record TestCsvRecord(string StringValue1, string StringValue2, int LineNumber);
and a CSV file without a line number column
StringValue1,StringValue2
Hello,World
Hello,Europe
Bonjour,Monde
I see from elsewhere that I should be mapping the LineNumber field using .Convert(record => record.Row.Parser.RawRow)
like so:
public class TestCsvRecordMap : ClassMap<TestCsvRecord>
{
public TestCsvRecordMap()
{
this.AutoMap(CultureInfo.InvariantCulture);
this.Map(x => x.LineNumber)
.Convert(record => record.Row.Parser.RawRow);
}
}
A simple test to use this is:
string csvData = "StringValue1,StringValue2\nHello,World\nHello,Europe\nBonjour,Monde";
CsvConfiguration defaultConfiguration = new(CultureInfo.InvariantCulture)
{
HasHeaderRecord = true,
MissingFieldFound = null,
HeaderValidated = null,
};
StringReader reader = new(csvData);
using var csv = new CsvReader(reader, defaultConfiguration);
csv.Context.RegisterClassMap<TestCsvRecordMap>();
var records = csv.GetRecords<TestCsvRecord>().ToList();
Assert.Equal(3, records.Count(x => x.LineNumber > 1));
But when I try to use this class map I get a System.ArgumentException : Incorrect number of arguments for constructor
error. I have tried to Ignore()
the column, Parameter()
mapping, setting it to Optional()
.