新しいAsp.net Identity Security Frameworkの使用に関するドキュメントはほとんどありません。
新しいロールを作成し、そこにユーザーを追加するために、できる限りのことをしてみました。 試したのは次のとおりです。https://stackoverflow.com/questions/19541101/add-role-in-asp-net-identity
これは、このブログから情報を得ているようです。Building a simple to-do application with asp.net identity and associating users with to-does.
モデルが変更されるたびに実行されるデータベースイニシャライザにコードを追加しました。しかし、RoleExists
関数で次のようなエラーが出て失敗します。
System.InvalidOperationException
occurred in mscorlib.dll エンティティタイプのIdentityRoleは、現在のコンテキストのモデルの一部ではありません。
protected override void Seed (MyContext context)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
// Create Admin Role
string roleName = "Admins";
IdentityResult roleResult;
// Check to see if Role Exists, if not create it
if (!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
ご協力お願いします。
いよいよです。
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if(!roleManager.RoleExists("ROLE NAME"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "ROLE NAME";
roleManager.Create(role);
}
上記のPetersのコードを改良して、以下のように使用できます。
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (!roleManager.RoleExists("Member"))
roleManager.Create(new IdentityRole("Member"));