[英]Automapper overrinding destination values that are not in source ONLY when mapping lists of objects
When trying to map a list of Source to a list of Destination automapper is overriding the Id so it becomes 00000000-0000-0000-0000-000000000000.当尝试 map 时,源列表到目标自动映射器列表正在覆盖 Id,因此它变为 00000000-0000-0000-0000-000000000000。
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(d => d.Name, opt => opt.MapFrom(dest => dest.Name))
.ForAllOtherMembers(opt => opt.Ignore());
});
var sourceList = new List<Source>
{
new Source
{
Name = "name1"
},
new Source
{
Name = "name2",
},
new Source
{
Name = "name3"
}
};
var destList = new List<Destination>
{
new Destination
{
Id = Guid.NewGuid()
},
new Destination
{
Id = Guid.NewGuid()
},
new Destination
{
Id = Guid.NewGuid()
}
};
var mapper = new Mapper(configuration);
var result = mapper.Map(sourceList, destList);
I've also tried using ValidateMemberList(MemberList.None)
but the effect is the same.我也尝试过使用ValidateMemberList(MemberList.None)
但效果是一样的。 This ONLY happens when the objects are in a list.这只发生在对象在列表中时。 Mapping between two objects works as expected.两个对象之间的映射按预期工作。 Am I missing some configuration option?我错过了一些配置选项吗?
EDIT: checking with make id in visual studio it seems it's replacing the objects in the destination with new ones instead of mapping values, is there any way to change this behavior or have it keep all non mapped properties from the initial destination object?编辑:在visual studio中检查make id,它似乎用新的对象而不是映射值替换目标中的对象,有没有办法改变这种行为或让它保留来自初始目标object的所有非映射属性?
It seems unintuitive to me but currently this is the intended behavior so I decided to just iterate and map each item individually.这对我来说似乎不直观,但目前这是预期的行为,所以我决定单独迭代和 map 每个项目。
for (var i = 0; i < sourceList.Count; i++)
{
var source = sourceList[i];
var destination= destList[i];
mapper.Map(source, destination);
}
For my use case I didn't think it was worth it to add a new a dependency on AutoMapper Collection and then also try to make it work with indexes somehow.对于我的用例,我认为在AutoMapper Collection上添加一个新的依赖项然后尝试以某种方式使其与索引一起使用是不值得的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.