How to Update Employee and Identity User with one to one/zero relation

≡放荡痞女 提交于 2019-12-04 07:11:01

问题


I am trying to update employee record and want to update identity user too.

If i update Identity User first separately For Example:

UserManager.Update(user);
Context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
Context.SaveChanges();

and then update the employee. maybe it is possible identity user updates with success but employee update process gets an error. so IdentityUser is updated now but the employee is not. how to handle this situation. please guide.

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;
}

Adding new record works fine. but when i update the record. i don't know how to update both records at once. For Example:

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;
}

回答1:


Without seeing the exception, I'm not sure what the issue is, but you could trying using an attached entity and set values like the following.

 var dbEmployee = Context.Emplyoees.SingleOrDefault(s => s.Id == employee.Id);
 if (dbEmployee!= null)
 Context.Entry(dbEmployee).CurrentValues.SetValues(employee);



回答2:


The User employee service should be

public bool UpdateEmployee(Employee employee)
{
    var existingEmployee = Context.Emplyoees.FirstOrDefault(s => s.Id == employee.Id);
    if (existingEmployee != null)
    {
        //do the update to the database 
        Context.Entry(existingEmployee).CurrentValues.SetValues(employee);
        Context.Entry(existingEmployee).State = System.Data.Entity.EntityState.Modified;
        return Context.SaveChanges() > 0;
    }
    else return false;
}


来源:https://stackoverflow.com/questions/55982875/how-to-update-employee-and-identity-user-with-one-to-one-zero-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!