【发布时间】:2016-04-24 05:50:58
【问题描述】:
我正在使用身份 3。我想在启动时为管理员用户播种。
我已将字符串 ids 转换为“int”ids,以 github 上的 SwiftCourier 为例。标识 3 在某些方面有所不同,这适用于 SwiftCourier 示例中显示的 id 的“int”设置,与 Identity 2 和“int”id 的设置相比。
我通过在我的用户后面放置“int”来做到这一点:
public class User : IdentityUser<int>{...}
在我的角色之后:
public class Role : IdentityRole<int>
在配置服务的 startup.cs 中我输入了这个:
services.AddIdentity<User, Role>(options => options.User.AllowedUserNameCharacters = null)
.AddEntityFrameworkStores<JobsDbContext, int>()
.AddUserStore<UserStore<User, Role, JobsDbContext, int>>()
.AddRoleStore<RoleStore<Role, JobsDbContext, int>>()
.AddDefaultTokenProviders();
然后我用它来播种角色,它适用于整数 id:
public static void EnsureRolesCreated(this IApplicationBuilder app)
{
var context = app.ApplicationServices.GetService<JobsDbContext>();
if (context.AllMigrationsApplied())
{
var roleManager = app.ApplicationServices.GetService<RoleManager<Role>>();
var Roles = new List<Role>();
Roles.Add(new Role { Name = "Admin", Description = "Users able to access all areas" });
Roles.Add(new Role { Name = "Technician", Description = "Users able to access just the schedule" });
foreach (var role in Roles)
{
if (!roleManager.RoleExistsAsync(role.Name.ToUpper()).Result)
{
roleManager.CreateAsync(role);
}
}
}
}
到目前为止一切顺利...我只想从一个管理员用户开始,这就是我失败的地方...
我使用了@Guy 提供的以下 Stackoverflow example。
我在 UserStore 中苦苦挣扎:
await new UserStore<User>(context).CreateAsync(userWithRoles.User);
它在“用户”上失败,这是我刚刚重命名的应用程序用户。
我得到的错误是:
The type 'JobsLedger.Models.Identity.User' cannot be used as type parameter 'TUser' in the generic type or method 'UserStore<TUser>'. There is no implicit reference conversion from 'JobsLedger.Models.Identity.User' to 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser<string>'.
似乎在抱怨我认为 id 是“int”这一事实
在这方面,如何使 UserStore 与“int”一起使用?如上所示,它在 Startup.cs 中设置为 int..
如果我必须创建一个与“int”一起使用的自定义“UserStore”..你如何在 Identity 3 中做到这一点?
【问题讨论】:
-
我举了一个将用户添加到角色的例子,它有帮助吗?如果确实如此,请将答案标记为正确答案
-
我刚刚做到了。我无法使用 int id 在此处创建用户,更不用说向用户添加角色了..它在用户存储上失败..
标签: asp.net-core asp.net-core-mvc asp.net-identity-3