2016-05-26 16 views
1

私はMVC5でIdentity 1.0エンティティフレームワークWebアプリケーションで作業しています。私のシードメソッドでは、最初の移行中にユーザーにロールを割り当てようとしています。 私はプロパティまたはインデクサ 'IdentityUserApplicationUserLogin、ApplicationUserRole、ApplicationUserClaim> .Rolesは' に割り当てることはできませんプロパティまたはインデクサ 'IdentityUser int、ApplicationUserLogin、ApplicationUserRole、ApplicationUserClaim>。ロール'を割り当てることができません - 読み取り専用

Role = "Admin" 

を入れたときに、私はエラーを取得する - それが、私は、これはどういう意味だけ

を読まれますアプリケーションを実行するときに、Webサイトで手動でロールを割り当てる必要がありますか?

Configuration.cs

 var roles = new List<ApplicationRole> 
     { 
      new ApplicationRole { Id = 1, Name = "Admin"}, 
      new ApplicationRole { Id = 2, Name = "User"}, 

     }; 
     roles.ForEach(s => context.Roles.AddOrUpdate(p => p.Name, s)); 
     context.SaveChanges(); 


     var passwordHash = new PasswordHasher(); 
     string password = passwordHash.HashPassword("[email protected]"); 

     var users = new List<ApplicationUser> 
     { 

      new ApplicationUser { UserName = "[email protected]", FirstMidName = "Jackie", LastName = "Chan", Email="[email protected]",PasswordHash = password, Roles = "Admin", 
       EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1,DepotID = 1,IsAdministrator = true,SecurityStamp = Guid.NewGuid().ToString()}, 


     users.ForEach(s => context.Users.AddOrUpdate(p => p.UserName, s)); 
     context.SaveChanges(); 

IdentityModel.cs

namespace RecreationalServicesTicketingSystem.Models 
{ 
    public class ApplicationUserLogin : IdentityUserLogin<int> { } 
    public class ApplicationUserClaim : IdentityUserClaim<int> { } 
    public class ApplicationUserRole : IdentityUserRole<int> { } 

    public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int> 
    { 
     public string Description { get; set; } 

     public ApplicationRole() : base() { } 
     public ApplicationRole(string name) 
      : this() 
     { 
      this.Name = name; 
     } 

     public ApplicationRole(string name, string description) 
      : this(name) 
     { 
      this.Description = description; 
     } 
    } 

    public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int> 
    { 
     public async Task<ClaimsIdentity> 
      GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager) 
     { 
      var userIdentity = await manager 
       .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
      return userIdentity; 
     } 

     public bool IsAdministrator { get; set; } 
     [StringLength(50, MinimumLength = 1)] 

     public string LastName { get; set; } 
     [StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")] 

     [Column("FirstName")] 
     public string FirstMidName { get; set; } 

     public string FullName 
     { 
      get { return FirstMidName + " " + LastName; } 
     } 
     [DataType(DataType.Date)] 
     [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] 
     public DateTime EnrollmentDate { get; set; } 
     public int DepartmentID { get; set; } 
     [ForeignKey("DepartmentID")] 
     public virtual Department Department { get; set; } 
     public int DepotID { get; set; } 
     [ForeignKey("DepotID")] 
     public virtual Depot Depot { get; set; } 
     public virtual ICollection<Ticket> Tickets { get; set; } 


    } 


    public class ApplicationDbContext 
     : IdentityDbContext<ApplicationUser, ApplicationRole, int, 
     ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim> 
    { 
     public ApplicationDbContext() 
      : base("DefaultConnection") 
     { 
     } 

     static ApplicationDbContext() 
     { 
      Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); 
     } 


     public static ApplicationDbContext Create() 
     { 
      return new ApplicationDbContext(); 
     } 


     public DbSet<Ticket> Tickets { get; set; } 
     public DbSet<Category> Categories { get; set; } 
     public DbSet<Department> Departments { get; set; } 
     public DbSet<Depot> Depots { get; set; } 


    } 



    public class ApplicationUserStore : 
    UserStore<ApplicationUser, ApplicationRole, int, 
    ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUserStore<ApplicationUser, int>, IDisposable 
    { 
     public ApplicationUserStore() 
      : this(new IdentityDbContext()) 
     { 
      base.DisposeContext = true; 
     } 

     public ApplicationUserStore(DbContext context) 
      : base(context) 
     { 
     } 
    } 


    public class ApplicationRoleStore 
    : RoleStore<ApplicationRole, int, ApplicationUserRole>, 
    IQueryableRoleStore<ApplicationRole, int>, 
    IRoleStore<ApplicationRole, int>, IDisposable 
    { 
     public ApplicationRoleStore() 
      : base(new IdentityDbContext()) 
     { 
      base.DisposeContext = true; 
     } 

     public ApplicationRoleStore(DbContext context) 
      : base(context) 
     { 
     } 
    } 

} 

役割コントローラは

namespace RecreationalServicesTicketingSystem.Controllers 
{ 
    //[Authorize(Roles = "Admin")] 
    public class RolesAdminController : Controller 
    { 

     public RolesAdminController() 
     { 

     } 

     public RolesAdminController(ApplicationUserManager userManager, 
      ApplicationRoleManager roleManager) 
     { 
      UserManager = userManager; 
      RoleManager = roleManager; 
     } 

     private ApplicationUserManager _userManager; 
     public ApplicationUserManager UserManager 
     { 
      get 
      { 
       return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
      } 
      set 
      { 
       _userManager = value; 
      } 
     } 

     private ApplicationRoleManager _roleManager; 
     public ApplicationRoleManager RoleManager 
     { 
      get 
      { 
       return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); 
      } 
      private set 
      { 
       _roleManager = value; 
      } 
     } 

     // 
     // GET: /Roles/ 
     public ActionResult Index() 
     { 
      return View(RoleManager.Roles); 
     } 

     // 
     // GET: /Roles/Details/5 
     public async Task<ActionResult> Details(int id) 
     { 
      if (id > 0) 
      { 
       var role = await RoleManager.FindByIdAsync(id); 
       // Get the list of Users in this Role 
       var users = new List<ApplicationUser>(); 

       // Get the list of Users in this Role 
       foreach (var user in UserManager.Users.ToList()) 
       { 
        if (await UserManager.IsInRoleAsync(user.Id, role.Name)) 
        { 
         users.Add(user); 
        } 
       } 

       ViewBag.Users = users; 
       ViewBag.UserCount = users.Count(); 
       return View(role); 
      } 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     } 

     // 
     // GET: /Roles/Create 
     public ActionResult Create() 
     { 
      return View(); 
     } 

     // 
     // POST: /Roles/Create 
     [HttpPost] 
     public async Task<ActionResult> Create(RoleViewModel roleViewModel) 
     { 
      if (ModelState.IsValid) 
      { 
       // Use ApplicationRole, not IdentityRole: 
       var role = new ApplicationRole(roleViewModel.Name); 
       var roleresult = await RoleManager.CreateAsync(role); 
       if (!roleresult.Succeeded) 
       { 
        ModelState.AddModelError("", roleresult.Errors.First()); 
        return View(); 
       } 
       return RedirectToAction("Index"); 
      } 
      return View(); 
     } 

     // 
     // GET: /Roles/Edit/Admin 
     public async Task<ActionResult> Edit(int id) 
     { 
      if (id > 0) 
      { 
       var role = await RoleManager.FindByIdAsync(id); 
       if (role == null) 
       { 
        return HttpNotFound(); 
       } 
       RoleViewModel roleModel = new RoleViewModel { Id = role.Id, Name = role.Name }; 
       return View(roleModel); 
      } 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     } 

     // 
     // POST: /Roles/Edit/5 
     [HttpPost] 

     [ValidateAntiForgeryToken] 
     public async Task<ActionResult> Edit([Bind(Include = "Name,Id")] RoleViewModel roleModel) 
     { 
      if (ModelState.IsValid) 
      { 
       var role = await RoleManager.FindByIdAsync(roleModel.Id); 
       role.Name = roleModel.Name; 
       await RoleManager.UpdateAsync(role); 
       return RedirectToAction("Index"); 
      } 
      return View(); 
     } 

     // 
     // GET: /Roles/Delete/5 
     public async Task<ActionResult> Delete(int id) 
     { 
      if (id > 0) 
      { 
       var role = await RoleManager.FindByIdAsync(id); 
       if (role == null) 
       { 
        return HttpNotFound(); 
       } 
       return View(role); 
      } 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     } 

     // 
     // POST: /Roles/Delete/5 
     [HttpPost, ActionName("Delete")] 
     [ValidateAntiForgeryToken] 
     public async Task<ActionResult> DeleteConfirmed(int id, string deleteUser) 
     { 
      if (ModelState.IsValid) 
      { 
       if (id > 0) 
       { 
        var role = await RoleManager.FindByIdAsync(id); 
        if (role == null) 
        { 
         return HttpNotFound(); 
        } 
        IdentityResult result; 
        if (deleteUser != null) 
        { 
         result = await RoleManager.DeleteAsync(role); 
        } 
        else 
        { 
         result = await RoleManager.DeleteAsync(role); 
        } 
        if (!result.Succeeded) 
        { 
         ModelState.AddModelError("", result.Errors.First()); 
         return View(); 
        } 
        return RedirectToAction("Index"); 
       } 
       else 
       { 
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
       } 
      } 
      return View(); 
     } 
    } 
} 

答えて

0

新しいApplicationUserオブジェクトの役割プロパティはApplicationUserRole項目のいるICollectionを期待しています。以下の例を参照してください。

new ApplicationUser 
{ 
    UserName = "[email protected]", 
    FirstMidName = "Jackie", 
    LastName = "Chan", 
    Email = "[email protected]", 
    PasswordHash = password, 
    Roles = 
    { 
     new ApplicationUserRole 
     { 
      RoleId = 1 
     } 
    }, 
    EnrollmentDate = DateTime.Parse("2016-02-18"), 
    DepartmentID = 1, 
    DepotID = 1, 
    IsAdministrator = true, 
    SecurityStamp = Guid.NewGuid().ToString() 
} 
関連する問題