我有下面的DTO,我需要将其映射到平面视图模型,这个想法是来自请求的一些属性是共享的,但可能会有一个名称列表.
public class ShinyDTO
{
public List<UserDetails> Users { get; set; }
public string SharedPropertyOne { get; set; }
public string SharedPropertyTwo { get; set; }
}
public class UserDetails
{
public string Title { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
}
public class MyRealClass
{
public string SharedPropertyOne {get;set;}
public string SharedPropertyTwo {get;set;}
public string Title {get;set;}
public string Forename {get;set;}
public string Surname {get;set;}
}
//This will map all the shared properties
MyRealClass request = Mapper.Map<MyRealClass>(dto);
foreach (var record in dto.Users){
//This bit overwrites the properties set above and then I only have the properties set for Forename, Surname, etc...
request = Mapper.Map<MyRealClass>(record);
}
我需要将其映射到MyRealClass列表中.我已经尝试创建单独的映射,然后在foreach中循环它,但这保持删除初始属性.
我也尝试设置第二个映射来忽略上面设置的属性,我无法使其工作,它仍然覆盖属性.
var autoMapperConfiguration = new MapperConfigurationExpression();
autoMapperConfiguration
.CreateMap<MyRealClass, UserDetails>()
.ForMember(c => c.SharedPropertyOne, d => d.Ignore())
.ForMember(c => c.SharedPropertyTwo, d => d.Ignore());
最佳答案 我认为你很接近,但你的问题是:
I need to map this into a list of
MyRealClass
…但是您尝试映射将MyRealClass映射到UserDetails.看起来你真的想要从UserDetails到MyRealClass的地图.
无论如何,这是实现这一目标的一种方法:
var autoMapperConfiguration = new MapperConfigurationExpression();
autoMapperConfiguration.CreateMap<UserDetails, MyRealClass>();
autoMapperConfiguration.CreateMap<ShinyDTO, MyRealClass>();
var results = new List<MyRealClass>();
foreach(var record in dto.Users) {
var mapped = Mapper.Map<MyRealClass>(dto);
Mapper.Map(record, mapped);
results.Add(mapped);
}
这里,第二个Mapper.Map调用将记录映射到映射,它不应该覆盖已经从ShinyDTO映射到MyRealClass的映射的值.
您也可以在ConstructUsing调用中获得所有这些,但这对我来说似乎更清晰.