如何使用一对一/零关系更新员工和身份用户 [英] How to Update Employee and Identity User with one to one/zero relation

查看:23
本文介绍了如何使用一对一/零关系更新员工和身份用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();

然后更新员工.也许身份用户更新可能成功,但员工更新过程出错.所以 IdentityUser 现在更新了,但员工没有.如何处理这种情况.请指导.

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

推荐答案

User 员工服务应该是

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

这篇关于如何使用一对一/零关系更新员工和身份用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆