【问题标题】:Is it possible/advisable to seed Users/Roles using the EFCore 2.1 Data Seeding system?是否可以/建议使用 EFCore 2.1 数据播种系统播种用户/角色?
【发布时间】:2018-06-07 13:39:49
【问题描述】:

从 EFCore 2.1 开始,可以使用 DbContext OnModelCreating 方法播种数据。

https://docs.microsoft.com/en-us/ef/core/modeling/data-seeding

然而,用户/角色的创建通常由 UserManager/RoleManager 处理。

现在,我可以手动创建角色或用户 - 但例如在用户的情况下,我需要自己散列密码(而且我不知道 UserManager 使用什么散列方法而不深入研究源)

有没有办法解决这个问题?还是应该像以前版本的 Entity Framework Core 一样坚持使用在启动时运行的静态播种方法?

【问题讨论】:

    标签: asp.net-core entity-framework-core


    【解决方案1】:

    如果您想将OnModelCreating 方法与HasData 方法一起使用,您可以这样做:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            ApplicationUser appUser = new ApplicationUser
            {
                UserName = "tester",
                Email = "tester@test.com",
                NormalizedEmail = "tester@test.com".ToUpper(),
                NormalizedUserName = "tester".ToUpper(),
                TwoFactorEnabled = false,
                EmailConfirmed = true,
                PhoneNumber = "123456789",
                PhoneNumberConfirmed = false
            };
    
            PasswordHasher<ApplicationUser> ph = new PasswordHasher<ApplicationUser>();
            appUser.PasswordHash = ph.HashPassword(appUser, "Your-PW1");
    
            modelBuilder.Entity<IdentityRole>().HasData(
                new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" },
                new IdentityRole { Name = "User", NormalizedName = "USER"}
            );
            modelBuilder.Entity<ApplicationUser>().HasData(
                appUser
            );
        }
    

    如果您在HasData 方法之外创建用户,则可以使用PasswordHasher。 它将为您散列密码。然后只需将创建的用户放入HasData,而不是在那里创建一个新用户。 我不知道这是否比启动时播种更好,但这是一种方法。

    【讨论】:

    • 这确实比seeding on startup 好,正如微软所说的The seeding code should not be part of the normal app execution,但他们也说.HasData() 不应该用于Data that requires calls to external API, such as ASP.NET Core Identity roles and users creation docs.microsoft.com/en-us/ef/core/modeling/…
    猜你喜欢
    • 2021-07-10
    • 2012-11-13
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多