我使用带有整数 ids的 Identity 3.0 播种得到了奇怪的结果。我正在播种角色 - 只有两个 - 使用这个:
using JobsLedger.DAL;
using JobsLedger.Models.Identity;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Identity;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
namespace JobsLedger.Models.Seeding
{
public static class SeedRoles
{
public static void EnsureRolesCreated(this IApplicationBuilder app)
{
var _context = app.ApplicationServices.GetService<JobsDbContext>();
if (_context.AllMigrationsApplied())
{
if (!_context.Roles.Any())
{
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).Result)
{
roleManager.CreateAsync(role);
}
}
_context.SaveChanges();
}
}
}
}
}
这是我从github 上的Unicorn 示例中获得的。
角色如下,带有一个名为 Description 的额外字段:
public class Role : IdentityRole<int>
{
public Role() : base() { }
public Role(string name) { Name = name; }
public string Description { get; set; }
}
在我的启动中,我在 configure() 方法中有这个:
app.EnsureRolesCreated();
我已将项目配置为通过 Startup.cs 重新创建数据库,使用:
serviceScope.ServiceProvider.GetService<JobsDbContext>().Database.Migrate();
如果数据库不存在,则在启动时创建数据库......很好 - 它可以工作。
现在,当我检查角色时,我要么只获得第二个角色,要么获得两个角色两次.. 4 条记录.. 或者,很少只有两条记录,这就是它的假设。
我试图检查方法中的角色,并在添加角色之前检查是否有任何角色。
我已经删除了表的内容,所以所有行并再次运行它,我只得到了 ID 为“2”的第二个角色......它的 ID 是两个似乎没问题,但为什么只有一条记录?
删除数据库并重新运行项目,现在它具有第二个角色,ID 为“1”......但仍然只有一条记录。
重写了该方法以更接近Unicorn 示例,认为这可能是我编写该方法的方式..
public static void EnsureRolesCreated(this IApplicationBuilder app)
{
var _context = app.ApplicationServices.GetService<JobsDbContext>();
if (_context.AllMigrationsApplied())
{
if (!_context.Roles.Any())
{
var roleManager = app.ApplicationServices.GetService<RoleManager<Role>>();
var Roles = new string[,]
{
{"Admin","Users able to access all areas" },
{"Technician","Users able to access just the schedule" }
};
for (int i = 0; i < Roles.GetLength(0); i++)
{
if (!roleManager.RoleExistsAsync(Roles[i, 0].ToUpper()).Result)
{
roleManager.CreateAsync(new Role { Name = Roles[i, 0], Description = Roles[i, 1] });
}
}
}
}
}
我第一次运行它时效果很好..删除了数据库并再次运行它..仅保存了第二条记录..然后我再次删除了数据库并第三次运行它并获得了 4 条记录..这两者角色两次??
我做错了吗?该代码似乎可以创建两个角色,但也许我错过了什么?有任何想法吗?