【问题标题】:Seed Entities AND Users, Roles?种子实体和用户、角色?
【发布时间】:2015-06-14 02:15:04
【问题描述】:

您如何播种用户、角色和应用特定实体?看起来好像 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");
    }
}

【问题讨论】:

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


    【解决方案1】:

    我没有从迁移中播种,而是使用上下文数据库初始化程序。我的上下文来自 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");
                }
    ...
    

    【讨论】:

    • 看起来不错,谢谢!有没有办法同时针对用户/角色等的默认数据库和实体的新 dbcontext 以使用一个初始化程序来播种?似乎 EF 为帐户管理/身份设置了自己的 DbContext,而作为开发人员,我们针对实体/模型的 crud 操作针对不同的 DbContext?我理解正确吗?
    • 我们将其设置为从 IdentityDbContext 派生,因此对于身份和业务类,我们只有 1 个初始化程序、迁移等。对于更大的架构,它可能会限制您将数据内容分离到不同的项目或存储库中的能力,但它对我们来说效果很好。 Julie Lerman 有几篇关于这个主题的好文章。 msdn.microsoft.com/en-us/magazine/jj883952.aspx
    • 谢谢,史蒂夫。所以在上面的例子中;在 if (!db.Users.Any()){} 之后,您将开始为业务类创建新对象?
    • 您可以从 Seed() 调用不同的例程,例如 InitializeBusinessObjects(context);对于查找表等内容。您还可以将该代码放在迁移配置 Seed() 方法中。
    • 知道如何在 EF Core 中执行此操作吗?
    猜你喜欢
    • 2013-10-17
    • 2016-10-03
    • 2018-08-10
    • 2018-02-28
    • 2015-11-02
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多