Home > database >  How can EF Core prevent seeding from being invoked multiple times in OnModelCreating()?
How can EF Core prevent seeding from being invoked multiple times in OnModelCreating()?

Time:09-13

According to documentation,

Typically OnModelCreating() is called only once when the first instance of a derived context is created. The model for that context is then cached and is for all further instances of the context in the app domain.

Now consider my code:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.ApplyConfiguration(new StudentConfiguration());
}
internal class StudentConfiguration : IEntityTypeConfiguration<Student>
{
    public void Configure(EntityTypeBuilder<Student> builder)
    {
        Console.WriteLine($">>>>>>>>>>>>>>>>>>>>>> {nameof(StudentConfiguration)}");
        builder.HasData(
            new Student
            {
                Name = "Albert Einstein",
                Age = 100
            },
            new Student
            {
                Name = "Isaac Newton",
                Age = 400
            }
        );
    }
}

When invoking dotnet ef database update, the seeding is invoked. So far it is understandable.

Now if I start the application, OnModelCreating() should be invoked to create models that will be cached for all further instances of the database context in the application domain.

I see a single

>>>>>>>>>>>>>>>>>>>>>> StudentConfiguration

for the first database access in the whole life of the application. However, I don't see a duplicate seeding in the database.

Restarting the application multiple times also does not cause multiple seeding. It is actually good but how can seeding happens just once recall that Configure() is invoked multiple times, each once per application domain?

CodePudding user response:

HasData fluent API is part of the so called EF Core Table Name

Migrations should look like this: enter image description here

  • Related