實體框架Core with Identity和ASP.NET Core 1.1 Seeding

asp.net-core entity-framework-core

我試著從我的數據庫中播種初始數據,但這個技術的信息非常糟糕。在尋找了許多選項之後,我發現我可以在這篇文章中如何發送IdentityRole和IdentityUser的實際數據

實體框架Core with Identity和ASP.NET Core RC2不在數據庫中創建用戶

但是用戶說在ConfigureServices中添加像Transient這樣的服務之後,調用配置這個服務,這個提示是怎麼回事?有想法嗎?

問候

一般承認的答案

Archer,為了將數據播種到ASP.NET核心中的數據庫,你應該首先創建一個類,你可以調用這個DbInitializer,它應該看起來像這樣。

public static class DbInitializer
{
    public async static void InitializeAync(ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        context.Database.EnsureCreated();

        // check if any users exist.
        if (context.Users.Any())
        {
            return;   // exit method, Database has been seeded
        }

        string[] roleNames = {"Admin", "Member" };
        IdentityResult roleResult;
        // loop through roleNames Array
        foreach (var roleName in roleNames)
        {
            var roleExist = await RoleManager.RoleExistsAsync(roleName);
            //check if role exists
            if (!roleExist)
            {
                // create new role
                roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
            }
        }

        //create an array of users 
        var users = new ApplicationUser[];
       {
            new ApplicationUser
            {
                FirstName = "John",
                LastName = "doe",
                UserName = "johndoe",
                Email = "johndoe@email.com",
            };

           new ApplicationUser
           {
               FirstName = "James",
               LastName = "doe",
               UserName = "jamesdoe",
               Email = "jamesdoe@email.com",
           };
        }

        //loop through users array
        foreach (ApplicationUser _user in users)
        {
            // create user
            await userManager.CreateAsync(_user, "pa$$w0rd");
            //add user to "Member" role
            await UserManager.AddToRoleAsync(_user, "Member");
        }

    }
}

接下來,您應該從Startup類中的Configure方法調用DbInitializer類中的InitializeAsync幫助器方法。像這樣

public async void Configure( ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
      DbInitializer.InitializeAync(context, userManager);
}

這應該可以解決問題



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow