The process of populating a database with an initial set of data
Data seeding is the process of populating a database with an initial set of data. There are several ways this can be accomplished in EF Core:
For example, the following are some available strategies:
Use migrations: In EF Core, seeding data can be associated with an entity type as part of the model configuration. Then EF Core migrations can automatically compute what insert, update or delete operations need to be applied when upgrading the database to a new version of the model.
OnModelCreating
:1modelBuilder.Entity<Blog>().HasData(new Blog { BlogId = 1, Url = "http://sample.com" });
2//To add entities that have a relationship the foreign key values need to be specified:
3modelBuilder.Entity<Post>().HasData(
4 new Post { BlogId = 1, PostId = 1, Title = "First post", Content = "Test 1" });
💡 If you need to apply migrations as part of an automated deployment you can create a SQL script that can be previewed before execution. (questo aspetto verrà ripreso nella seconda parte del corso)
Use custom initialization logic: you can use context.Database.EnsureCreated()
to create a new database containing the seed data, for example for a test database or when using the in-memory provider or any non-relational database. Note that if the database already exists, EnsureCreated()
will neither update the schema nor seed data in the database. For relational databases you shouldn’t call EnsureCreated()
if you plan to use Migrations.
1protected static void CleanDatabase(DbContext context)
2 {
3 ConsoleWriteLines("Deleting and re-creating database...");
4 context.Database.EnsureDeleted();
5 context.Database.EnsureCreated();
6 ConsoleWriteLines("Done. Database is clean and fresh.");
7 }
Si veda anche la documentazione specifica Microsoft.