Используйте AutoMapper, это не так сложно.
Startup.cs ConfigureServices:
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new RegisterViewModelProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
Создайте класс RegisterViewModelProfile. (Я обычно помещаю их в соответствующий файл класса viewmodel, в вашем случае это файл RegisterViewModel.cs. Другие создают один MapperProfile.cs и помещают все классы Profile в этот файл, но из c вы можете создавать отдельные файлы для каждого. )
public class RegisterViewModelProfile : Profile
{
public RegisterViewModelProfile()
{
CreateMap<RegisterViewModel, ApplicationUser>()
.ForMember(dest=>dest.UserName, opt=>opt.MapFrom(src=>src.Email))
.ForMember(dest=>dest.NotificationPreference , opt=>opt.MapFrom(src=> Enum.GetName(typeof(NotificationPreference), NotificationPreference.None) ));
//you dont need to map the other attributes because they have the same name and type in VM and in Model so AutoMapper does it automagically
//you can map the other way around too if you need to the same way, and you can even do conditional mapping and/or overwrite data etc
CreateMap<ApplicationUser, RegisterViewModel>()
.ForMember(dest => d.Email, opt => opt.MapFrom(src => "Masked because of GDPR"));
}
}
В вашем контроллере введите маппер и сделайте маппинг, когда вам нужно сделать:
public class JobsteplogsController : Controller
{
private readonly IMapper _mapper;
public UserController(JobManagerContextCustom context, IMapper mapper)
{
_mapper = mapper;
}
public async Task<IActionResult> Register(RegisterViewModel registerModel)
{
if (ModelState.IsValid)
{
ApplicationUser user = _mapper.Map<ApplicationUser>(registerModel);
await userManager.CreateAsync(user, registerModel.Password);
}
return View(registerModel);
}
}