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)
您需要做的是在源类型和目标类型之间创建映射:
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)
| 归档时间: |
|
| 查看次数: |
2007 次 |
| 最近记录: |