1

我试图搜索很多,并尝试不同的选项,但似乎没有任何工作。AutoMapper:保留目标值,如果该属性不存在于源

我使用ASP.net身份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(); 
+0

试试“UseDestinationValue”,而不是“忽略” –

+0

它仍然在用户对象中保持为空。 –

回答

3

所有你需要的是创造你的源和目标类型之间的映射:

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 
+1

它会复制它们,假定您的域模型中具有相同的属性名称和类型。 –

+1

然后我想你是做错了事,而不是我在答案中显示的方式。如我的答案**所示,Mapper.Map方法**将将源对象中存在的所有属性值复制到目标对象中,而不会影响dest对象中的任何其他属性。 –

+0

你是对的。对不起。我没有注意到,我应该从Map方法中删除。 谢谢lotttttt。我删除了我的评论,因此任何未来的用户都不会被误导。 –

相关问题