I have problem with automapper
Here I have two objects:
Object 1:
public class First
{
......
public IList<string> ImportantList{ get; set; }
......
}
Object 2:
public class Second
{
.....
public IList<ImportantListClass> ImportantList{ get; set; }
.....
}
class:
public class ImportantListClass
{
public string Name{ get; set; }
}
I try to use automapper to map First object to Second but my destination ImportantList is Empty. I have the same number of object in destination class but Name property is null.
I try:
CreateMap<Second, First>()
.ForMember(z => z.ImportantList, map => map.MapFrom(z =>
z.ImportantList.Select(x => x.Name).ToList()))
.ReverseMap();
But it not change anything Is their any better way to do this
@EDIT
I ADD this:
CreateMap<First, Second>();
CreateMap<ImportantListClass, string>()
.ConvertUsing(source => source.Name);
CreateMap<string, ImportantListClass>()
.ForMember(z => z.Name, z=> z.MapFrom(d => d));
Thanks for help!
You need to use ConvertUsing
and add a map from ImportantListClass
to string
:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Second, First>();
cfg.CreateMap<ImportantListClass, string>()
.ConvertUsing(source => source.Name);
});
var mapper = config.CreateMapper();
var second = new Second
{
Id = 22,
ImportantList = new List<ImportantListClass>
{
new ImportantListClass { Name = "Name1" },
new ImportantListClass { Name = "Name2" }
}
};
var first = mapper.Map<First>(second);