如何执行db.SaveChanges()然后再次更新数据库?

时间:2016-05-25 22:11:02

标签: asp.net sql-server asp.net-mvc post controller

POST期间的我的控制器中,如何更新USERS实体,然后使用新创建的UserID在我的USERROLES表格中为其分配角色。下面是我目前的代码,它在尝试保存第二组更改时出错。

我的USERROLES表格包含UserIDRoleID的组合。 UserID中的USERS在插入表格时会自动生成。

如果有人可以告诉我如何真正解决这个问题,那将是非常棒的 - 我对ASP MVC来说还是一个新手。

using (var db = new SwinTCSEntities()) // initialise db object
{
    // add values to USERS
    db.USERS.Add(new USERS
    {
        FirstName = model.FirstName,
        LastName = model.LastName,
        Username = model.Username,
        Password = Crypto.HashPassword("pass1234"),
        Email = model.Email,
        OfficeNo = model.OfficeNo,
        PhoneNo = model.PhoneNo,
        RegistrationDateTime = DateTime.Now,
        MeetingNotifications = true,
        SubmissionNotifications = true,
        TeamAssignNotifications = true,
        OverdueNotifications = true
    });
    db.SaveChanges(); // this goes through fine

    if (db.USERS.Any(x => x.Username == model.Username)) // it's able to get the new user value
    {
        if (model.IsAdmin && !model.IsStudent)
        {
            db.USERROLES.Add(new USERROLES
            {
                UserID = db.USERS.First(x => x.Username == model.Username).UserID,
                RoleID = db.ROLES.First(x => x.Name == "Admin").RoleID,
                DateAdded = DateTime.Now
            });
            // It errors here with a concurrency error
            db.SaveChanges();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

using (var db = new SwinTCSEntities()) // initialise db object
{
    // create USERS object
    var user = new USERS
    {
        FirstName = model.FirstName,
        LastName = model.LastName,
        Username = model.Username,
        Password = Crypto.HashPassword("pass1234"),
        Email = model.Email,
        OfficeNo = model.OfficeNo,
        PhoneNo = model.PhoneNo,
        RegistrationDateTime = DateTime.Now,
        MeetingNotifications = true,
        SubmissionNotifications = true,
        TeamAssignNotifications = true,
        OverdueNotifications = true
    };


   //load the admin role in the EF context and add it to this new user
        if (model.IsAdmin && !model.IsStudent)
        {
            var adminRole = db.ROLES.First(x => x.Name == "Admin");
            user.USERROLES.Add(new USERROLES
            {
                Role = adminRole,
                DateAdded = DateTime.Now
            });
        }


    //add the user to the USERS set  
    db.USERS.Add(user);

    db.SaveChanges(); // EF is smart enough to link the entities on SaveChanges

}

答案 1 :(得分:0)

不要使用SaveChanges 2次,我可以显示其他解决方案: 我变瘦,所以你的新用户有唯一的ID吗?所以使用try和catch方法或类似的东西:

var user = new ApplicationUser { UserName = userViewModel.Email, Email = userViewModel.Email };
            var adminresult = await UserManager.CreateAsync(user, userViewModel.Password);

            //Add User to the selected Roles 
            if (adminresult.Succeeded)
            {
                if (selectedRoles != null)
                {
                    var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                        ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
                        return View();
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", adminresult.Errors.First());
                ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
                return View();

            }
            return RedirectToAction("Index");

您可以根据需要更改所选角色。抱歉我的英语。