6

I am using TextFieldParser to parse a CSV file to import into a database using EntityFramework.

TextFieldParser returns each line of the CSV file as a string[]. In order to save the objects, I need to build an object from each line. Is there any way to do this using AutoMapper?

My object structure is like this:

public class Person
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
}

And my CSV lines are in the following format:

FirstName,MiddleName,LastName,Address,PhoneNumber

Ryan Kohn
  • 13,079
  • 14
  • 56
  • 81

1 Answers1

16

This can be done fairly easily in AutoMapper by doing something like this:

Mapper.CreateMap<string[], Person>()
    .ForMember(p => p.FirstName, opts => opts.MapFrom(s => s[0]))
    .ForMember(p => p.MiddleName, opts => opts.MapFrom(s => s[1]))
    .ForMember(p => p.LastName, opts => opts.MapFrom(s => s[2]))
    .ForMember(p => p.Address, opts => opts.MapFrom(s => s[3]))
    .ForMember(p => p.PhoneNumber, opts => opts.MapFrom(s => s[4]));

Keep in mind that this mapping is dependent on the order of the values in the CSV file.

Ryan Kohn
  • 13,079
  • 14
  • 56
  • 81