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

Saa*_*ooq 1 asp.net automapper asp.net-mvc-5 asp.net-identity asp.net-identity-2

我尝试了很多搜索,然后尝试了其他选项,但似乎没有任何效果。

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

我试着做:

Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.ForMember(dest => dest.Email, opt => opt.Ignore());
Run Code Online (Sandbox Code Playgroud)

但是映射后我仍然将Email设置为null:

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
user = Mapper.Map<UpdateProfileViewModel, ApplicationUser>(model);
Run Code Online (Sandbox Code Playgroud)

我也试过了,但是没有用:

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;
    }
Run Code Online (Sandbox Code Playgroud)

然后:

 Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.IgnoreAllNonExisting();
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

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

Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>();
Run Code Online (Sandbox Code Playgroud)

然后执行映射:

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
Run Code Online (Sandbox Code Playgroud)

  • 然后,我想您做错了什么,而不是我在回答中所显示的方式。如我的答案中所示,`Mapper.Map`方法会将源对象中存在的所有属性值复制到目标对象中,而不会影响dest对象中的任何其他属性。 (2认同)