Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use AutoMapper to map a string array to an object

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

like image 705
Ryan Kohn Avatar asked Sep 09 '14 15:09

Ryan Kohn


1 Answers

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.

like image 75
Ryan Kohn Avatar answered Oct 23 '22 22:10

Ryan Kohn