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。我刪除了我的評論,因此任何未來的用戶都不會被誤導。 –

相關問題