USER 使用 Entity Framework 将新角色更新到数据库中

USER Update with new role into database with Entity Framework

我遇到 updating/edit 用户分配新角色或从(1 或 2)更改角色的问题。角色保持不变,没有异常或错误。

注意:我在此处发布屏幕截图,因为我想准确显示我所看到的内容。

我有一个 User class 角色和城市相关 class 在里面:

public class User
{   
    public City CityId { get; set; }

    public virtual Role Role { get; set; }

    public bool IsInRole(int id)
    {
        return Role != null && Role.Id == id;
    }       
}

Role table 只有 2 个角色,管理员 ID=1,访客 ID=2。

我在更新现有用户的角色时遇到问题。

我想在这里做的是我想通过简单地更新用户并在角色字段中传递 1 来授予用户管理员权限,如下所示:

我可以通过此字段将 1 或 2 个 ID 传递给控制器​​,并设法通过角色 ID 获得 "admin":

因为我在 USER 中有所需的 ROLE 对象:

我仍然无法在数据库中更新具有管理员角色的用户。它仍然有 Guest 角色 ID。

User class 中的 CityID 情况相同。

如有任何帮助,我们将不胜感激

您需要找到该特定用户的 ID,例如:

public void UserEdit(int?id //id is your parameter here)
{
   //This is what you need.

    User user= db.User.Find(id);
    user.Role = //this is the new Role if this user
    user.CityId = //city id here
}

更新用户:

public void UpdateUser(User user)
{
   db.Entry(user).State = EntityState.Modified;
   db.SaveChanges();

}

您需要用户 table 而不是角色 table..

//样本class

public class User_Table
{   
    public int ID { get; set; }

    public string name { get; set; }

    public int RoleID { get; set; }
}

这个 table 是您需要更新的角色,而不是上面示例中的角色 table。

The thing is you have to find the id first then make it sure the Role table should be unmodified:

public void Update(User users // this is your object`enter code here)
{
    using(_db)
    {
        User user= db.User.Find(users.id);
        user.Role_id = users.Role_id; // this is what you want to change.
        _db.Entry(Role).State = EntityState.Unchanged;
        _db.SaveChanges();
    }
}

Hope That will Help. Cheers

你传递了用户的完整对象,它会改变另一个Table的状态,这就是为什么在将数据存储更改为另一个新对象之后,首先将用户对象按原样获取,然后更新并保持状态角色不变 Table 我希望它运作良好

 public ActionResult UpdateUser(User newUser)
    {
        newUser.City = new City { Id = Convert.ToInt32(fdata["CityList"]) };
        dbcontext db = new dbcontext();
        if (ModelState.IsValid)
        {
            using (db)
            {
                User oldUser = db.Users.Find(newUser.Id);
                oldUser.Role = newUser.Role;

                db.Entry(newUser.Role).State = EntityState.Unchanged;
                db.SaveChanges();
                return View();
            }