我試圖搜索很多,並嘗試不同的選項,但似乎沒有任何工作。AutoMapper:保留目標值,如果該屬性不存在於源
我使用ASP.net身份2.0,我有UpdateProfileViewModel。更新用戶信息時,我想將UpdateProfileViewModel映射到ApplicationUser(即身份模型);但我想保留這些值,我從用戶的數據庫中獲得了這些值。即用戶名&電子郵件地址,不需要更改。
我試圖做:
Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.ForMember(dest => dest.Email, opt => opt.Ignore());
,但我仍然獲得電子郵件爲空映射後:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
user = Mapper.Map<UpdateProfileViewModel, ApplicationUser>(model);
我也試過,但沒有作品:
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType));
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
然後:
Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.IgnoreAllNonExisting();
試試「UseDestinationValue」,而不是「忽略」 –
它仍然在用戶對象中保持爲空。 –