![](/img/trans.png)
[英]Automapper mapping multiple lists from source to single list on destination
[英]Automapper overrinding destination values that are not in source ONLY when mapping lists of objects
當嘗試 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);
我也嘗試過使用ValidateMemberList(MemberList.None)
但效果是一樣的。 這只發生在對象在列表中時。 兩個對象之間的映射按預期工作。 我錯過了一些配置選項嗎?
編輯:在visual studio中檢查make id,它似乎用新的對象而不是映射值替換目標中的對象,有沒有辦法改變這種行為或讓它保留來自初始目標object的所有非映射屬性?
這對我來說似乎不直觀,但目前這是預期的行為,所以我決定單獨迭代和 map 每個項目。
for (var i = 0; i < sourceList.Count; i++)
{
var source = sourceList[i];
var destination= destList[i];
mapper.Map(source, destination);
}
對於我的用例,我認為在AutoMapper Collection上添加一個新的依賴項然后嘗試以某種方式使其與索引一起使用是不值得的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.