【问题标题】:AutoMapper: Keep Destination Value if the property doesnt exists in sourceAutoMapper:如果源中不存在该属性,则保留目标值
【发布时间】:2016-06-10 17:27:33
【问题描述】:

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

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

【问题讨论】:

  • 尝试“UseDestinationValue”而不是“Ignore”
  • 它在用户对象中仍然保持为空。

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


【解决方案1】:

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

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

【讨论】:

  • 假设您在域模型中具有相同的属性名称和类型,它将复制它们。
  • 那么我想你做错了什么,而不是我在回答中显示的方式。 Mapper.Map 方法,如我的回答所示,会将源对象中存在的所有属性值复制到目标对象中,而不会影响目标对象中的任何其他属性。
  • 你是对的。我很抱歉。我没有注意到,我应该从 Map 方法中删除 。非常感谢。我删除了我的 cmets,所以任何未来的用户都不会被误导。
猜你喜欢
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2017-01-08
相关资源
最近更新 更多