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

时间:2016-02-27 12:16:03

标签: asp.net asp.net-mvc-5 asp.net-identity automapper asp.net-identity-2

我试图搜索很多,并尝试不同的选项,但似乎没有任何工作。

我正在使用ASP.net Identity 2.0,我有UpdateProfileViewModel。更新用户信息时,我想将UpdateProfileViewModel映射到ApplicationUser(即身份模型);但是我想保留这些值,我是从用户的数据库中获取的。即用户名&电子邮件地址,不需要更改。

我尝试过:

Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.ForMember(dest => dest.Email, opt => opt.Ignore());

但是我在映射后仍然将电子邮件视为null:

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();

1 个答案:

答案 0 :(得分:4)

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

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