使用asp.net身份更新用户角色 [英] Updating user role using asp.net identity

查看:217
本文介绍了使用asp.net身份更新用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题。虽然使用下面的下面的code键更改用户的当前角色我得到一个异常的消息类似如下:

  [HttpPost]
    [ValidateAntiForgeryToken]
    公共虚拟的ActionResult编辑(用户用户,串角色)
    {
        如果(ModelState.IsValid)
        {
            VAR oldUser = DB.Users.SingleOrDefault(U => u.Id == user.Id);
            VAR oldRoleId = oldUser.Roles.SingleOrDefault()角色ID。
            VAR oldRoleName = DB.Roles.SingleOrDefault(R = GT; r.Id == oldRoleId).Name点;
            如果(oldRoleName!=角色)
            {
                Manager.RemoveFromRole(user.Id,oldRoleName);
                Manager.AddToRole(user.Id,作用);
            }
            DB.Entry(用户).STATE = EntityState.Modified;            返回RedirectToAction(MVC.User.Index());
        }
        返回查看(用户);
    }

附加型Models.Entities.User的实体失败,因为同类型的另一实体已经有相同的主键值。这可以用'附加'方法或设置实体'不变'或'修改',如果图中的任何实体有冲突的关键值的状态时发生。这可能是因为一些实体是新的,但尚未收到数据库生成的键值。在这种情况下使用添加方法或添加实体状态跟踪图,然后设置非新的实体,以'不变'或'修改'的状态,适当的。

是否有人知道一个很好的解决这个问题呢?


解决方案

的问题是,你的经理和DB没有使用相同的DbContext。所以,当你从数据库到管理范围内发送的用户将处理它作为一个新之一 - 那么你不能从角色中删除。你有两种方式去这里。最简单的是从你的经理获得用户。

  [HttpPost]
[ValidateAntiForgeryToken]
公共虚拟的ActionResult编辑(用户用户,串角色)
{
    如果(ModelState.IsValid)
    {
        //此行非常重要,
        VAR oldUser = Manager.FindById(user.Id);
        VAR oldRoleId = oldUser.Roles.SingleOrDefault()角色ID。
        VAR oldRoleName = DB.Roles.SingleOrDefault(R = GT; r.Id == oldRoleId).Name点;        如果(oldRoleName!=角色)
        {
            Manager.RemoveFromRole(user.Id,oldRoleName);
            Manager.AddToRole(user.Id,作用);
        }
        DB.Entry(用户).STATE = EntityState.Modified;        返回RedirectToAction(MVC.User.Index());
    }
    返回查看(用户);
}

更优雅的方式是开始使用像AutoFac(的DI-框架HTTPS://$c$c.google.com/p/autofac/wiki/MvcIntegration ),并设置您的DbContext为InstancePerApiRequest

<$p$p><$c$c>builder.RegisterType<YourDbContext>().As<DbContext>().InstancePerApiRequest();

I have the following problem. While using the following code below to change the user's current role i am getting an exception with the message like below:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public virtual ActionResult Edit(User user, string role)
    {
        if (ModelState.IsValid)
        {
            var oldUser = DB.Users.SingleOrDefault(u => u.Id == user.Id);
            var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId;
            var oldRoleName = DB.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name;
            if (oldRoleName != role)
            {
                Manager.RemoveFromRole(user.Id, oldRoleName);
                Manager.AddToRole(user.Id, role);
            }
            DB.Entry(user).State = EntityState.Modified;

            return RedirectToAction(MVC.User.Index());
        }
        return View(user);
    }

Attaching an entity of type 'Models.Entities.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Does anybody know a good solution to this problem ?

解决方案

The problem is that your Manager and DB doesn't use the same DbContext. So when you send an user from the context of your DB to the Manager it will handle it as a "new" one - and then you cant remove it from the role. You have two ways to go here. The easiest is to get the User from your Manager.

[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Edit(User user, string role)
{
    if (ModelState.IsValid)
    {
        // THIS LINE IS IMPORTANT
        var oldUser = Manager.FindById(user.Id);
        var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId;
        var oldRoleName = DB.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name;

        if (oldRoleName != role)
        {
            Manager.RemoveFromRole(user.Id, oldRoleName);
            Manager.AddToRole(user.Id, role);
        }
        DB.Entry(user).State = EntityState.Modified;

        return RedirectToAction(MVC.User.Index());
    }
    return View(user);
}

The more elegant way is to start using an DI-framework like AutoFac (https://code.google.com/p/autofac/wiki/MvcIntegration) and set your DbContext as InstancePerApiRequest.

builder.RegisterType<YourDbContext>().As<DbContext>().InstancePerApiRequest();

这篇关于使用asp.net身份更新用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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