Whenever we create our database using model classes in entity framework core, after initial or first migration our database tables remains empty.
We can seed or insert initial data by using below steps.
Create Model Class.
In first step we have created our model class
Create Connection String
Open appsettings.json file and add ConnectionStrings like mentioned below
Refer model in DbConectext class
First Migration
Next we will open Package Manager console (View >> Other Windows >> Package Manager Console. Once Package Manager console is launched we will execute our first migration
Update Database
In next step we will run update-database command from package manager console to sync our changes with database.
Once update-database command is finished we can connect to database from Visual Studio by launching SQL Server Object Explorer ( View >> SQL Server Object Explorer)
We can found our database inside (localdb)\MSSQLLocalDB >> Database >> {{ Your Database Name }}
In above screenshot DemoDB is our database and PostModels is the name of the table
Initially PostModels table is empty
In order to create table with some initial records we use seed method.
So first we will revert our last migration.
In last step we have updated database with update-database command so we can't directly use remove-migration command here.
So first we have to query __EFMigrationsHistory table which contains all the migration.
To remove last migration(which was InitialMigration) we have to restore database to migration which was before InitialMigration (which is CreateIdentitySchema), so we will issue below mentioned command from package manager console
We have only one row in __EFMigrationsHistory table now
If we refresh our database we found that now we don't have PostModels table in database now.
Now we will open our DbConectext class and below method to create PostModels table with some initial data
In next step we will add migration follow by update-database command
Now if we check PostModels table in database then we will found it contains 2 rows.