Я пытаюсь обновить запись о сотруднике и хочу обновить также личность пользователя.
Если я сначала обновляю пользователя идентичности, например, отдельно:
UserManager.Update(user);
Context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
Context.SaveChanges();
, а затем обновляю сотрудника.может быть, это возможно, если пользователь успешно обновляет личность, но в процессе обновления сотрудника возникает ошибка.поэтому IdentityUser
сейчас обновляется, а сотрудник нет.как справиться с этой ситуацией.пожалуйста, руководство.
public class Employee
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string AppUserId { get; set; }
[ForeignKey("AppUserId")]
public virtual AppUser AppUser { get; set; }
}
public class AppUser : IdentityUser<string, AppUserLogin, AppUserRole, AppUserClaim>, IUser<string>
{
public AppUser()
{
this.Id = Guid.NewGuid().ToString();
}
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<AppUser, string> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsActive { get; set; }
}
public JsonResult Create(EmployeeVM evm, AppUserVM appUser)
{
var jsonResult = new JsonResult();
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
if (ModelState.IsValid)
{
var user = new AppUser();
evm.CreatedDate = DateTime.Now.Date;
appUser.PasswordHash = "dummypass";
user = Mapper.Map<AppUser>(appUser);
var employee = Mapper.Map<Employee>(evm);
employee.AppUser = user;
try
{
if (userService.CreateEmployee(employee))
{
jsonResult.Data = new { Success = true, message = "Success Added Record"};
}
}
catch (Exception ex)
{
jsonResult.Data = new { Success = false, message =ex.Message};
}
}
else
{
jsonResult.Data = new { Success = false, message = ModelErrors() };
}
return jsonResult;
}
public bool CreateEmployee(Employee employee)
{
Context.Employees.Add(employee);
return Context.SaveChanges()>0;
}
Добавление новой записи работает нормально.но когда я обновляю запись.я не знаю, как обновить обе записи одновременно.Например:
public JsonResult Edit(EmployeeVM evm, AppUserVM appUserVM)
{
ModelState.Remove(nameof(evm.CreatedDate));
var jsonResult = new JsonResult();
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
if (ModelState.IsValid)
{
appUserVM.UserName = appUserVM.Email;
var user = UserManager.FindById(evm.UserId);
user.Email = appUserVM.Email;
user.UserName = appUserVM.UserName;
user.FirstName = appUserVM.FirstName;
user.LastName = appUserVM.LastName;
user.IsActive = appUserVM.IsActive;
user.PhoneNumber = appUserVM.PhoneNumber;
var employee = Mapper.Map<Employee>(evm);
employee.AppUser = user;
employee.Id = evm.Id;
employee.AppUserId = user.Id;
try
{
if(userService.UpdateEmployee(employee))
jsonResult.Data = new { Success = true, message = "Success" };
}
catch (Exception ex)
{
jsonResult.Data = new { Success = false, message = ex.Message };
}
}
else
{
jsonResult.Data = new { Success = false, message = ModelErrors() };
}
return jsonResult;
}
public bool UpdateEmployee(Employee employee)
{
Context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
return Context.SaveChanges() > 0;
}