我试图搜索很多,并尝试不同的选项,但似乎没有任何工作。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”,而不是“忽略” –
它仍然在用户对象中保持为空。 –