0

I have the following code on DataContext:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration<CollectionSite>(new CollectionSiteMap());
        modelBuilder.ApplyConfiguration<TestOrderAlcoholResult>(new TestOrderAlcoholResultMap());
        //.... other configurations

        modelBuilder.Entity<ButtonStyle>().HasData(new ButtonStyle()
        {
            Label = "Sharp edges",
            Style = "border-radius: 0",
            IsDefault = true,
            Id = 1
        });
        modelBuilder.Entity<ColorScheme>().HasData(new ColorScheme()
        {
            Primary = "#a21521",
            Secondary = "#fcf7f8",
            Text = "#ced3dc",
            Background = "#4e8097",
            Shade = "#90c2e6",
            IsDefault = true,
            Id = 1
        });
        //.... seed other data

        base.OnModelCreating(modelBuilder);
    }

but data is not added to tables after update-database. What is wrong?

Oleg Sh
  • 8,496
  • 17
  • 89
  • 159

1 Answers1

0

The OnModelCreating called when you changed your Models or make changes in your DbContext then use Add-Migration and update-database.

OnModelCreating does not run every time when you use update-database.

According to Microsoft documentation this is better way to use Seed Data

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

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<DbContext>();
            DbInitializer.InitializeData(context);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while seeding the database.");
        }
    }

    host.Run();
}
public static class DbInitializer
{
    public static void InitializeData(DbContext context)
    {
        context.Database.EnsureCreated();
        context.ButtonStyle.Add(new ButtonStyle()
        {
            Label = "Sharp edges",
            Style = "border-radius: 0",
            IsDefault = true,
            Id = 1
        });
        context.ColorScheme.Add(new ColorScheme()
        {
            Primary = "#a21521",
            Secondary = "#fcf7f8",
            Text = "#ced3dc",
            Background = "#4e8097",
            Shade = "#90c2e6",
            IsDefault = true,
            Id = 1
        });
        context.SaveChanges();
    }
}

In this case InitializeData is checked every time your program is run, and if there is no record in the database, a new record is saved in the database again.

Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
  • I got "SqlException: Cannot insert explicit value for identity column in table 'DeviceModel' when IDENTITY_INSERT is set to OFF." if record already exists – Oleg Sh Aug 27 '20 at 15:23
  • @OlegSh Show your `DeviceModel` model – Farhad Zamani Aug 27 '20 at 15:34
  • @OlegSh Set **IDENTITY_INSERT** to on in `SQL`.Run this query in SQL `SET IDENTITY_INSERT DeviceModel ON`. This [link](https://stackoverflow.com/questions/7063501/how-to-turn-identity-insert-on-and-off-using-sql-server-2008) maybe helpful for you – Farhad Zamani Aug 27 '20 at 15:35