EF Core 2.1 Identity tables empty after HasData() seeding












2














I am trying to seed my Identity tables with the EF Core 2.1 HasData pattern, the code executes but nothing is inserted into the tables.

My DBContext class code:



public partial class IdentityDBContext : IdentityDbContext<IdentityUser>
{
public IdentityDBContext(DbContextOptions<IdentityDBContext> options)
: base(options)
{
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

IdentityRole RootRole = new IdentityRole
{
Id = Guid.NewGuid().ToString(),
Name = IdentityDBContext.RoleTypes.RootAdmin,
NormalizedName = "Root Admin"
};
builder.Entity<IdentityRole>().HasData(RootRole);

IdentityUser AdminUser = new IdentityUser
{
Id = Guid.NewGuid().ToString(),
UserName = "m@soze.biz",
Email = "m@soze.biz",
NormalizedUserName = "m@soze.biz".ToUpper(),
NormalizedEmail = "m@soze.biz".ToUpper(),
EmailConfirmed = true
};
builder.Entity<IdentityUser>().HasData(AdminUser);

builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
{
UserId = AdminUser.Id,
RoleId = RootRole.Id
});
}
}


In Startup.cs in the Configure method I have:



using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<IdentityDBContext>();
IdentityContext.Database.Migrate();
}


I can step through the OnModelCreating code executing without an exception however no records are added to the tables, both AspNetUsers and AspNetRoles are empty.



Any suggestions on why this isn't working?










share|improve this question




















  • 1




    Did you create a new EF migration, after adding the has data code?
    – Aman B
    Nov 20 at 10:51










  • I did try adding a migration after adding the HasData code but it seems I didn't rerun the application to push that migration out. I knew it was something simple I was missing, Thanks Aman! In case anyone else comes across this and has the same issue, in the package manager I ran 'Add-Migration Update-Database -Context IdentityDBContext' then executed the app and the migrations were pushed to the DB.
    – Mike Rowley
    Nov 20 at 17:11


















2














I am trying to seed my Identity tables with the EF Core 2.1 HasData pattern, the code executes but nothing is inserted into the tables.

My DBContext class code:



public partial class IdentityDBContext : IdentityDbContext<IdentityUser>
{
public IdentityDBContext(DbContextOptions<IdentityDBContext> options)
: base(options)
{
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

IdentityRole RootRole = new IdentityRole
{
Id = Guid.NewGuid().ToString(),
Name = IdentityDBContext.RoleTypes.RootAdmin,
NormalizedName = "Root Admin"
};
builder.Entity<IdentityRole>().HasData(RootRole);

IdentityUser AdminUser = new IdentityUser
{
Id = Guid.NewGuid().ToString(),
UserName = "m@soze.biz",
Email = "m@soze.biz",
NormalizedUserName = "m@soze.biz".ToUpper(),
NormalizedEmail = "m@soze.biz".ToUpper(),
EmailConfirmed = true
};
builder.Entity<IdentityUser>().HasData(AdminUser);

builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
{
UserId = AdminUser.Id,
RoleId = RootRole.Id
});
}
}


In Startup.cs in the Configure method I have:



using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<IdentityDBContext>();
IdentityContext.Database.Migrate();
}


I can step through the OnModelCreating code executing without an exception however no records are added to the tables, both AspNetUsers and AspNetRoles are empty.



Any suggestions on why this isn't working?










share|improve this question




















  • 1




    Did you create a new EF migration, after adding the has data code?
    – Aman B
    Nov 20 at 10:51










  • I did try adding a migration after adding the HasData code but it seems I didn't rerun the application to push that migration out. I knew it was something simple I was missing, Thanks Aman! In case anyone else comes across this and has the same issue, in the package manager I ran 'Add-Migration Update-Database -Context IdentityDBContext' then executed the app and the migrations were pushed to the DB.
    – Mike Rowley
    Nov 20 at 17:11
















2












2








2







I am trying to seed my Identity tables with the EF Core 2.1 HasData pattern, the code executes but nothing is inserted into the tables.

My DBContext class code:



public partial class IdentityDBContext : IdentityDbContext<IdentityUser>
{
public IdentityDBContext(DbContextOptions<IdentityDBContext> options)
: base(options)
{
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

IdentityRole RootRole = new IdentityRole
{
Id = Guid.NewGuid().ToString(),
Name = IdentityDBContext.RoleTypes.RootAdmin,
NormalizedName = "Root Admin"
};
builder.Entity<IdentityRole>().HasData(RootRole);

IdentityUser AdminUser = new IdentityUser
{
Id = Guid.NewGuid().ToString(),
UserName = "m@soze.biz",
Email = "m@soze.biz",
NormalizedUserName = "m@soze.biz".ToUpper(),
NormalizedEmail = "m@soze.biz".ToUpper(),
EmailConfirmed = true
};
builder.Entity<IdentityUser>().HasData(AdminUser);

builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
{
UserId = AdminUser.Id,
RoleId = RootRole.Id
});
}
}


In Startup.cs in the Configure method I have:



using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<IdentityDBContext>();
IdentityContext.Database.Migrate();
}


I can step through the OnModelCreating code executing without an exception however no records are added to the tables, both AspNetUsers and AspNetRoles are empty.



Any suggestions on why this isn't working?










share|improve this question















I am trying to seed my Identity tables with the EF Core 2.1 HasData pattern, the code executes but nothing is inserted into the tables.

My DBContext class code:



public partial class IdentityDBContext : IdentityDbContext<IdentityUser>
{
public IdentityDBContext(DbContextOptions<IdentityDBContext> options)
: base(options)
{
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

IdentityRole RootRole = new IdentityRole
{
Id = Guid.NewGuid().ToString(),
Name = IdentityDBContext.RoleTypes.RootAdmin,
NormalizedName = "Root Admin"
};
builder.Entity<IdentityRole>().HasData(RootRole);

IdentityUser AdminUser = new IdentityUser
{
Id = Guid.NewGuid().ToString(),
UserName = "m@soze.biz",
Email = "m@soze.biz",
NormalizedUserName = "m@soze.biz".ToUpper(),
NormalizedEmail = "m@soze.biz".ToUpper(),
EmailConfirmed = true
};
builder.Entity<IdentityUser>().HasData(AdminUser);

builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
{
UserId = AdminUser.Id,
RoleId = RootRole.Id
});
}
}


In Startup.cs in the Configure method I have:



using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<IdentityDBContext>();
IdentityContext.Database.Migrate();
}


I can step through the OnModelCreating code executing without an exception however no records are added to the tables, both AspNetUsers and AspNetRoles are empty.



Any suggestions on why this isn't working?







c# asp.net-core asp.net-identity ef-core-2.1






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 6:27









Foo

1




1










asked Nov 20 at 1:02









Mike Rowley

215




215








  • 1




    Did you create a new EF migration, after adding the has data code?
    – Aman B
    Nov 20 at 10:51










  • I did try adding a migration after adding the HasData code but it seems I didn't rerun the application to push that migration out. I knew it was something simple I was missing, Thanks Aman! In case anyone else comes across this and has the same issue, in the package manager I ran 'Add-Migration Update-Database -Context IdentityDBContext' then executed the app and the migrations were pushed to the DB.
    – Mike Rowley
    Nov 20 at 17:11
















  • 1




    Did you create a new EF migration, after adding the has data code?
    – Aman B
    Nov 20 at 10:51










  • I did try adding a migration after adding the HasData code but it seems I didn't rerun the application to push that migration out. I knew it was something simple I was missing, Thanks Aman! In case anyone else comes across this and has the same issue, in the package manager I ran 'Add-Migration Update-Database -Context IdentityDBContext' then executed the app and the migrations were pushed to the DB.
    – Mike Rowley
    Nov 20 at 17:11










1




1




Did you create a new EF migration, after adding the has data code?
– Aman B
Nov 20 at 10:51




Did you create a new EF migration, after adding the has data code?
– Aman B
Nov 20 at 10:51












I did try adding a migration after adding the HasData code but it seems I didn't rerun the application to push that migration out. I knew it was something simple I was missing, Thanks Aman! In case anyone else comes across this and has the same issue, in the package manager I ran 'Add-Migration Update-Database -Context IdentityDBContext' then executed the app and the migrations were pushed to the DB.
– Mike Rowley
Nov 20 at 17:11






I did try adding a migration after adding the HasData code but it seems I didn't rerun the application to push that migration out. I knew it was something simple I was missing, Thanks Aman! In case anyone else comes across this and has the same issue, in the package manager I ran 'Add-Migration Update-Database -Context IdentityDBContext' then executed the app and the migrations were pushed to the DB.
– Mike Rowley
Nov 20 at 17:11














1 Answer
1






active

oldest

votes


















0














For your issue, it is caused that Migrate only applied the pending migrations, it would not detect the changes after you change IdentityDBContext.



When you create project with Identity, it will automatically create the first migrations, and then even through, you changed IdentityDBContext, Migrate will only apply the first migrations without your other operations.



Here are two options for you:





  • For first initialize the database, you could try code below which will seed the data.



            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
    {
    var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
    IdentityContext.Database.EnsureCreated();
    }


  • The second option is that you already tried. Before run Migrate, run Add-Migration to generate the migrations for new changes.







share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384778%2fef-core-2-1-identity-tables-empty-after-hasdata-seeding%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    For your issue, it is caused that Migrate only applied the pending migrations, it would not detect the changes after you change IdentityDBContext.



    When you create project with Identity, it will automatically create the first migrations, and then even through, you changed IdentityDBContext, Migrate will only apply the first migrations without your other operations.



    Here are two options for you:





    • For first initialize the database, you could try code below which will seed the data.



              using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
      var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
      IdentityContext.Database.EnsureCreated();
      }


    • The second option is that you already tried. Before run Migrate, run Add-Migration to generate the migrations for new changes.







    share|improve this answer


























      0














      For your issue, it is caused that Migrate only applied the pending migrations, it would not detect the changes after you change IdentityDBContext.



      When you create project with Identity, it will automatically create the first migrations, and then even through, you changed IdentityDBContext, Migrate will only apply the first migrations without your other operations.



      Here are two options for you:





      • For first initialize the database, you could try code below which will seed the data.



                using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
        var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        IdentityContext.Database.EnsureCreated();
        }


      • The second option is that you already tried. Before run Migrate, run Add-Migration to generate the migrations for new changes.







      share|improve this answer
























        0












        0








        0






        For your issue, it is caused that Migrate only applied the pending migrations, it would not detect the changes after you change IdentityDBContext.



        When you create project with Identity, it will automatically create the first migrations, and then even through, you changed IdentityDBContext, Migrate will only apply the first migrations without your other operations.



        Here are two options for you:





        • For first initialize the database, you could try code below which will seed the data.



                  using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
          {
          var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
          IdentityContext.Database.EnsureCreated();
          }


        • The second option is that you already tried. Before run Migrate, run Add-Migration to generate the migrations for new changes.







        share|improve this answer












        For your issue, it is caused that Migrate only applied the pending migrations, it would not detect the changes after you change IdentityDBContext.



        When you create project with Identity, it will automatically create the first migrations, and then even through, you changed IdentityDBContext, Migrate will only apply the first migrations without your other operations.



        Here are two options for you:





        • For first initialize the database, you could try code below which will seed the data.



                  using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
          {
          var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
          IdentityContext.Database.EnsureCreated();
          }


        • The second option is that you already tried. Before run Migrate, run Add-Migration to generate the migrations for new changes.








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 at 7:54









        Tao Zhou

        4,75121128




        4,75121128






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384778%2fef-core-2-1-identity-tables-empty-after-hasdata-seeding%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            Origin of the phrase “under your belt”?