[英]Automapper - Map list of string to list of object with string property
I have problem with automapper我有自动映射器的问题
Here I have two objects:这里我有两个对象:
Object 1: Object 1:
public class First
{
......
public IList<string> ImportantList{ get; set; }
......
}
Object 2: Object 2:
public class Second
{
.....
public IList<ImportantListClass> ImportantList{ get; set; }
.....
}
class: 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.我尝试使用自动映射器到 map 第一个 object 到第二个,但我的目的地重要列表是空的。 I have the same number of object in destination class but Name property is null.我在目标 class 中有相同数量的 object,但名称属性是 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
:您需要使用ConvertUsing
并将 map 从ImportantListClass
添加到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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.