身份:为什么没有找到新创建的角色?

时间:2016-10-10 15:53:00

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

我正在开发一个MVC应用程序,我有一个表单来创建一个角色。表单中的数据正确地发送到post create action方法。这种方法的签名是:

[HttpPost]
public async Task<ActionResult> Create([Bind(Include = "Name")] AppRole appRole, string [] PrivsChecked)

基本上,这意味着创建一个角色,并附加为角色选择的权限,就像在表单上选择的用户一样。问题是,在为角色分配权限时,找不到新创建的角色。部分代码如下:

    public async Task<ActionResult> Create([Bind(Include = "Name")] AppRole appRole, string [] PrivsChecked)
      {
      if (PrivsChecked == null || PrivsChecked.Length == 0)
         {
          return Json(new { status = "error", message = "At least one privilege must be selected." });
          }
          else
           {
              if (ModelState.IsValid)
                {
                 IdentityResult result
                                = await RoleManager.CreateAsync(new AppRole(appRole.Name));
                 if (result.Succeeded)
                            {
                                var approleToUpdate = db.IdentityRoles.Where(i => i.Id == appRole.Id).FirstOrDefault();
.
.
.

appRoleToUpdate被指定为null,但至少达到了该代码,这意味着角色创建成功。在控制器中声明为全局变量db的{​​{1}}上下文如下:

private AppIdentityDbContext db = new AppIdentityDbContext();

奇怪的是,Edit方法中也存在非常相似的代码,在这种情况下,找到了using IdentityDevelopment.Models; using Microsoft.AspNet.Identity; namespace IdentityDevelopment.Infrastructure { public class AppIdentityDbContext : IdentityDbContext<AppUser> { public AppIdentityDbContext() : base("IdentityDb") { } static AppIdentityDbContext() { Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit()); } public static AppIdentityDbContext Create() { return new AppIdentityDbContext(); } public System.Data.Entity.DbSet<IdentityDevelopment.Models.AppRole> IdentityRoles { get; set; } public System.Data.Entity.DbSet<IdentityDevelopment.Models.AppPrivilege> AppPrivileges { get; set; } } public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext> { } } 。如何在同一方法中找到新创建的角色?这与方法的异步性质有什么关系吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

您使用新名称创建了新角色,但您还没有真正了解其ID。尝试检查名称(确保它是唯一的),这应该让你回到你的角色:

var approleToUpdate = db.IdentityRoles.Where(i => i.Name == appRole.Name).FirstOrDefault();