2016-10-10 30 views
0

我正在研究一個MVC應用程序,並且我有一個表單來創建一個角色。表單中的數據將正確發送到後期創建操作方法。這種方法的簽名是:身份:爲什麼沒有找到新創建的角色?

[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被分配到零,但至少達到該代碼,這意味着角色創建成功。該db背景下,宣佈爲在控制器中的全局變量private AppIdentityDbContext db = new AppIdentityDbContext();,如下:

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

} 

奇怪的是,在編輯方法存在非常相似的代碼爲好,在這種情況下,appRoleToUpdate發現。我能做些什麼來讓新創建的角色在同一個方法中找到?這與方法的異步性質有什麼關係?

謝謝。

回答

2

您使用新名稱創建了新角色,但您還不知道其ID。嘗試檢查名稱(確保它是獨一無二的),這應該返回你的角色:

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

謝謝,它的工作。 – ITWorker

相關問題