c# - 种子实体和用户、角色?

标签 c# entity-framework asp.net-mvc-5 entity-framework-migrations

您如何为用户、角色和应用特定实体提供种子?似乎 IdentityModel 以它自己的上下文为目标?

internal sealed class Configuration : DbMigrationsConfiguration<Project.Models.SchoolContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(Project.Models.SchoolContext context)
    {
        // Seed the Entities
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" }            
        //    );
        //
    }
}

对比

protected override void Seed(Project.Models.ApplicationDbContext context)
{
    if (!context.Roles.Any(r => r.Name == "AppAdmin"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "AppAdmin" };
        manager.Create(role);
    }

    if (!context.Users.Any(u => u.UserName == "founder"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser {UserName = "founder"};

        manager.Create(user, "ChangeItAsap!");
        manager.AddToRole(user.Id, "AppAdmin");
    }
}

最佳答案

我不从迁移中播种,而是使用上下文数据库初始化程序。我的上下文源自 IdentityDbContext,因此我使用此方法为用户和角色设定种子:

从 ctor 调用初始化程序:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    private readonly IHttpContextBaseWrapper _httpContextBaseWrapper;

    static ApplicationDbContext()
    {
        // Set the database intializer which is run once during application start
        // This seeds the database with admin user credentials and admin role
        Database.SetInitializer(new ApplicationDbInitializer());
    }
...

然后是我的种子码:

public class ApplicationDbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext>
{
    protected override void Seed(ApplicationDbContext context)
    {
        InitializeIdentityForEF(context);
        base.Seed(context);
    }

    public static void InitializeIdentityForEF(ApplicationDbContext db)
    {

        if (!db.Users.Any())
        {
            var roleStore = new RoleStore<IdentityRole>(db);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            var userStore = new UserStore<ApplicationUser>(db);
            var userManager = new UserManager<ApplicationUser>(userStore);

            // Add missing roles
            var role = roleManager.FindByName("Admin");
            if (role == null)
            {
                role = new IdentityRole("Admin");
                roleManager.Create(role);
            }

            // Create test users
            var user = userManager.FindByName("admin");
            if (user == null)
            {
                var newUser = new ApplicationUser()
                {
                    UserName = "admin",
                    FirstName = "Admin",
                    LastName = "User",
                    Email = "xxx@xxx.net",
                    PhoneNumber = "5551234567",
                    MustChangePassword = false
                };
                userManager.Create(newUser, "Password1");
                userManager.SetLockoutEnabled(newUser.Id, false);
                userManager.AddToRole(newUser.Id, "Admin");
            }
...

关于c# - 种子实体和用户、角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29526215/

相关文章:

c# - MVC5模型不记录文本框的文本值

c# - 文本框替换文本

c# - 编码的 UI 测试生成器导致我的 Visual Studio 应用程序崩溃

asp.net - 在MVC5应用中更改默认标题颜色

c# - 使用存储库模式使用 ThenIclude 急切加载实体

c# - Code First 导航属性被保留但未加载

c# - 使用自定义 View 基础在 Razor View 中调用异步函数

c# - 非静态私有(private)或 protected 事件存在哪些用例?

javascript - 将 javascript 图像 blob 保存到 ASP.NET Core Controller

c# - ASP.NET MVC 5项目中VS2017连接MySQL