简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM