如何以一对一/零关系更新员工和身份用户

时间:2019-05-04 13:11:38

标签: c# asp.net asp.net-mvc-5 entity-framework-6

我正在尝试更新员工记录,也想更新身份用户。

如果我先分别更新身份用户 例如:

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

2 个答案:

答案 0 :(得分:0)

没有看到异常,我不确定是什么问题,但是您可以尝试使用附加的实体并设置如下所示的值。

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

答案 1 :(得分:0)

用户员工服务应为

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