【问题标题】:How to Update Employee and Identity User with one to one/zero relation如何使用一对一/零关系更新员工和身份用户
【发布时间】:2019-09-22 18:31:10
【问题描述】:

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

如果我先单独更新身份用户 例如:

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

【问题讨论】:

  • 可以添加例外吗?
  • 如果它们在同一个 DbContext 上,则先更新员工,然后更新用户 - 这些将由 SaveChanges 内部的 EF 包装到同一事务中,由 @987654331 调用@。如果不同的 DbContext,那么自己创建一个事务 va using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)){ /* your updates here */ }
  • 我正在使用与 IdentityDbContext 继承的相同 Db 上下文。但是我在使用用户管理器``` public AppUserManager UserManager { get { return _userManager ?? HttpContext.Current.GetOwinContext().Get(); } 私有集 { userManager = value; } } ``` 使用 UserManager 和 GetOwinContext().Get();这是同一个上下文吗?

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


【解决方案1】:

没有看到异常,我不确定问题出在哪里,但您可以尝试使用附加实体并设置如下值。

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

【讨论】:

    【解决方案2】:

    User 员工服务应该是

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

    【讨论】:

    • Employee 和 IdentityUser 有一对一/零关系我想一次更新员工记录和 identityUser 记录.. 你给定的代码会更新 Employee 和 IdentityUser 记录吗?
    • 我根据您的代码进行了编辑。用户管理器.更新(用户);将更新用户,而 abouve 函数将在用户之后更新员工,如果您想同时更新两者,请查看此答案 stackoverflow.com/questions/55692042/… 以了解如何同时链接两个表和更新
    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多