What is Data Seeding in .NET Core

Data seeding allows us to provide initial data during the creation of a database. Then, EF Core migrations will automatically determine what insert, update or delete operations need to be applied when upgrading the database to a new version of the model.
So let’s create some seed data now. For this, we need to override the OnModelCreating method in the Context class which we created in EF tutorial.

Copy the below code and paste it in context file. and change the code as per your need
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
      modelBuilder.Entity().HasData( 
               new Student 
              {
                    FirstName = "Student 1",
                    ID = new System.Guid("9b4cc8d2-78ab-47f0-41bc-08d6d9379d75") 
               },
               new Student  
              { 
                    FirstName = "Student 2", 
                    ID = new System.Guid("c13d7414-7d42-43c3-b934-08d6d9ed80a3")
              } 
            );
 }


Here we are creating two students in our database.

Now Run the command:
Add-Migration Name
and then update database by running following commands
Update-DataBase

it will update the database with the seed data which we provided

Limitations of seed data

  • The primary key value needs to be specified even if it's usually generated by the database. It will be used to detect data changes between migrations.
  • Previously seeded data will be removed if the primary key is changed in any way.
Therefore this feature is most useful for static data that's not expected to change outside of migrations and does not depend on anything else in the database, for example ZIP codes.

No comments: