Entity Framework Core Code-First Approach with Seed Data
We initially develop the classes for our domain entities using the EF-Core Code-initially methodology. Afterwards, we use migrations to generate the database from our code. The Data-First strategy, in which we build our database first and then create the classes that match, is the antithesis of this.
How Does Entity Framework Core Code-First Approach Work?
- Model First: First, we create a class where we write properties as columns of a data table.
- Database Linked Instance: A DbSet<TEntity> can be used to query and save instances of our Model. LINQ queries against a DbSet<TEntity> will be translated into queries against the database.
- Seed Data: When you want your data table prefilled with data, the OnModelCreating override method is required.
- Adding the Migration: Using Terminal, we can add or update our migrations from classes to the database.
Code Example
- Add a Database Connection to your project’s Program.cs file, you can define your connection string in the appsettings.json file.
Create your Model with getter and setter properties.
[Key] attribute will indicate the field with identity key and primary key constraints. [Required] attribute will make the field required and Not-Null field.- Create an ApplicationDbContext class to manage DbContext entities.
Categories will be your table name in the database
- To add seed data, prefilled into your Category table.
- To add the changes to the database, open a Package Manager Console, Go to Tools > NuGet Package Manager > Package Manager Console.
- When Package Manage Console opened; type add-migration <migration_name>, this will create a migration_name.cs file, which you can assess to check if the correct table is being created.
- If the migration comment throws error; Make sure you have a package installed Microsoft.EntityFrameworkCore.Tools
- To reflect all changes to the database, type update-database.
- Now you can check your table in the Database.