Home > Software design >  How to seed users, roles when I have TWO DbContext, a) IdentityDbContext & b) AppDbContext
How to seed users, roles when I have TWO DbContext, a) IdentityDbContext & b) AppDbContext

Time:01-19

normally I would put the code for seeding users in the OnModelCreating() Its not an issue with one DbContext.

Recently it was recommended to separate identity's DbContext from the App's DbContext, which has added two DbContexts and some confusion.

  1. public UseManagementDbContext(DbContextOptions<UseManagementDbContext> options) : base(options) // security/users separation
  2. public AppDbContext(DbContextOptions<MyDbContext> options) : base(options)

But when you have two separate DbContexts, How do I seed the user / role data?

  1. IdentityDbContext -- this has all the <IdentityUser> context for seeding

  2. AppDbContext -- this does NOT have <IdentityUser> context, but my Migrations use this context.


Can you please help how to seed the user and role data, and is part of the migrations or startup etc.


Update: using core 6 sample, @Zhi Lv - how do I retrofit into program.cs my seedData when the app is fired up

My Program.cs was from created originally from the ASP Core 3.1 template, it looks like this, what should I refactor, (oddly in the link enter image description here

Since, you are using two DBcontext, you can also create multiple static methods to seed the data.

More detail information, you can check the enter image description here

[Note] From the screenshot, we can see that by default the EmailConfirmed column is False. If you enabled the Email Confirm operation, you need to change the value to True, then you can login success.

Update 2:

For the previous version: such as Asp.net 5 or Asp.net core 3.1, you could add the seed initializer in the Program.cs with the following code:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                SeedData.Initialize(services);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred seeding the DB.");
            }
        }

        host.Run();

    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Reference: Add the seed initializer.

  •  Tags:  
  • Related