1

I am creating a football manager game. I have used identity 2.0 as it will work well for my registration and login. I was able to add the extra tables that were needed but now I need to seed the data such as teams and players to these table. Any idea how to do so? The extra tables were created in the identity models using migrations. Here is a picture of the tables I am using.

tables

Jasen
  • 14,030
  • 3
  • 51
  • 68
DaveReg
  • 23
  • 4
  • To Seed Identity, see [here](http://stackoverflow.com/questions/29526215/seed-entities-and-users-roles/29547994#29547994). Regarding the other tables, see [here](http://stackoverflow.com/questions/36896475/database-initialization-in-entity-framework-code-first/36897524#36897524) – Steve Greene Jan 21 '17 at 21:21

2 Answers2

0

In the Migrations folder, there is a file called Configuration.cs with the Seed method that you can use to create some seed data.

protected override void Seed(ApplicationDbContext context)
{
    //  This method will be called after migrating to the latest version.

    //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
    //  to avoid creating duplicate seed data. E.g.

    //add roles
    context.Roles.AddOrUpdate(p => p.Id,
        new IdentityRole()
        {
            Id = EnumUtility<AspNetRoles>.GetAppRoleId(AspNetRoles.None),
            Name = AspNetRoles.None.ToString()
        });
}

Just run update-database and you should have data in your tables.

Ali Baig
  • 3,819
  • 4
  • 34
  • 47
0

There are 2 Seed() methods available - one in certain initializers such as CreateDatabaseIfNotExist that is run whenever the database is created. The other is the migration Seed() which runs whenever you apply a migration via update-database.

Since it runs with every migration, you want to make sure you don't duplicate your data. You could do this by checking for existence:

if (!context.Teams.Any())
{
     context.Teams.Add(new Team { Name = "Team A" });
     context.Teams.Add(new Team { Name = "Team B" });

}

But there is a better way designed specifically for migrations called AddOrUpdate:

protected override void Seed(ApplicationDbContext context)
{
    context.Teams.AddOrUpdate(
        team => team.Id,   // put the key or unique field here
        new Team
        {
            Id = 1,
            Name = "Team 1"
        },
        new Team
        {
            Id = 2,
            Name = "Team 2"
        });

    context.SaveChanges();
}
Steve Greene
  • 12,029
  • 1
  • 33
  • 54