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

问题描述 投票:0回答:2

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

我正在使用 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();
asp.net asp.net-mvc-5 asp.net-identity automapper asp.net-identity-2
2个回答
8
投票

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

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

0
投票

Mapper 在分配给目标对象时将返回一个新对象,而您必须使用 Map 将源和目标作为参数传递。

public class SourceObjectModel 
{
    public string Name { get; set; }
}

public class DestinationObjectModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

SourceObjectModel sourceObj = new SourceObjectModel() {Name = "foo"};
DestinationObjectModel destinObj = new DestinationObjectModel(){Id = 1};


/*update only "name" in destinObj*/
_mapper.Map<SourceObjectModel, DestinationObjectModel>(sourceObj, destinObj);
© www.soinside.com 2019 - 2024. All rights reserved.