dotnet / EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6
https://docs.microsoft.com/ef/
Creative Commons Attribution 4.0 International
1.56k stars 1.94k forks source link

Documentation improvement about data-seeding #4703

Open andremarcondesteixeira opened 1 month ago

andremarcondesteixeira commented 1 month ago

Type of issue

Missing information

Description

Article: https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding

The article does mention that Migrations should be used to apply data seeding.

However, one could just interpret this as "you need to call .Migrate()" in your code (like I did).

// Program.cs

// hidden code...

using (var scope = app.Services.CreateScope())
{
    scope.ServiceProvider
            .GetRequiredService<ApplicationDbContext>()
            .Database
            .Migrate();
}

app.Start();

After days of banging my head against the wall, trying to figure out why my initial users and roles were not being created, googling for solutions, searching StackOverflow, asking ChatGPT, reading ASP.NET source code, and with no success after many, many, many, many, maaaaaaaaaaaany hours of stress and headaches, I realized by accident that if I delete my migrations, then OnModelCreated does seed the data.

It looks like Entity Framework only applies data seed from model.Entity<Foo>.HasData(bar) when creating migrations.

So, my suggestion is to make it clear that data is ONLY seeded during the migration creation phase, NOT during runtime.

Please make this clearer.

Page URL

https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding

Content source URL

https://github.com/dotnet/EntityFramework.Docs/blob/main/entity-framework/core/modeling/data-seeding.md

Document Version Independent Id

822e8923-2647-f573-0c74-66af903776d8

Article author

@AndriySvyryd