AutoMapper:如果源中不存在 属性,则保留目标值

AutoMapper: Keep Destination Value if the property doesnt exists in source

我尝试了很多搜索,并尝试了不同的选项,但似乎没有任何效果。

我正在使用 ASP.net Identity 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();

您只需在源类型和目标类型之间创建一个映射:

Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>();

然后执行映射:

UpdateProfileViewModel viewModel = ... this comes from your view, probably bound
ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
Mapper.Map(viewModel, user);

// at this stage the user domain model will only have the properties present
// in the view model updated. All the other properties will remain unchanged
// You could now go ahead and persist the updated 'user' domain model in your
// datastore