1
votes

I'm trying to map a csv file to a POCO class using CsvHelper. When I try to csv.GetRecords<Client>(), I'm getting an error that states:

Field with name 'InID' does not exist. You can ignore missing fields by setting MissingFieldFound to null.

However, I'm actually mapping the InID property of my class using a Constant:

Map(c => c.InID).Constant(true);

Based on what I see in the documentation, using Constant should not require a field in the CSV file.

Here is my code:

public class Client{
  public int Id {get; set;}
  public int FirstName {get; set;}
  public int LastName {get; set;}
  public bool InID {get; set;}
  public bool InMH {get; set;}
}

public class IDMap : ClassMap<Client>
{
    public IDMap(){
        Map(c => c.InID).Constant(true);
        Map(c => c.FirstName).Name("Consumer_First_Name");
        Map(c => c.LastName).Name("Consumer_Last_Name");
    }
}

//In my Controller
List<Client> clients;
using(var csv = new CsvReader(reader))
{
    csv.Configuration.RegisterClassMap<IDMap>();
    clients = csv.GetRecords<Client>().ToList();
}

I'm not seeing much difference between what I'm doing and the CsvHelper example.

Note

I did try adding csv.Configuration.MissingFieldFound = null but all that does is cause CsvHelper to skip the InID mapping completely rather than populating the property with a constant value.

2

2 Answers

3
votes

Seems to be a bug. The example doesn't work either. You can use ConvertUsing instead.

public class IDMap : ClassMap<Client>
{
    public IDMap()
    {
        Map(c => c.InID).ConvertUsing((IReaderRow row) => true);
        Map(c => c.FirstName).Name("Consumer_First_Name");
        Map(c => c.LastName).Name("Consumer_Last_Name");
    }
}
2
votes

As a workaround, you can specify that this is actually not a column in the source file by specifying an index of -1.

Map(c => c.InID).Index(-1).Constant(true);