Understanding Code First Approach of Entity Framework Core

Learn the Entity Framework Core Code First workflow for creating tables, adding columns, changing constraints, deleting tables, and defining relationships.

Understanding Code First Approach of Entity Framework Core cover

Introduction

In this article, we will understand the Code First approach of Entity Framework Core in ASP.NET Core. The examples show how to create tables, delete tables, add columns, remove columns, change column size, make columns not null, add primary keys, and create relationships.

Topics Covered

  • What is Entity Framework Core?
  • Create a new ASP.NET Core project
  • Set up Entity Framework Core and add a new table
  • Add a new column in a table
  • Delete a column from a table
  • Change column size
  • Make a column not null
  • Delete a table
  • Add a primary key column
  • Add a relationship (foreign key)

What Is Entity Framework Core?

Entity Framework Core is the newer version of Entity Framework after EF 6.x. It is open-source, lightweight, extensible, and cross-platform.

It is an object-relational mapping framework that helps developers access and store data in a database without writing all the data access code manually.

Create a New ASP.NET Core Project

Step 1

Open Visual Studio and create a new project.

Step 2

Select an ASP.NET Core project and click Next.

Select ASP.NET Core project

Step 3

Enter the project name and location, then click Create.

Project name and location

Step 4

Choose the .NET Core framework and an empty template, then click Create.

Choose empty template

Set Up Entity Framework Core and Add a New Table

Step 1

Install the required NuGet packages.

Manage NuGet packages

The article uses these packages:

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.Extensions.Configuration

Step 2

Create a Model folder for your entity classes.

Create Model folder

Step 3

Add a Book entity class with your desired properties.

Add Book class

Step 4

Add a context class that inherits from DbContext.

Create context class

Add a constructor that accepts DbContextOptions and passes it to the base constructor, then add a DbSet<Book> property.

Step 5

Add the connection string to appsettings.json.

The article uses a local SQL Server connection and Windows authentication.

Step 6

Register the DbContext in Startup.

The article adds CFDbContext in ConfigureServices and reads the connection string using GetConnectionString.

Step 7

Open Package Manager Console.

Open Package Manager Console

Step 8

Create the first migration.

Add-Migration Init

Migration created

The migration creates a snapshot file and the initial migration file.

Migration folder

Step 9

Apply the migration.

Update-Database

Update database

The Books table is now created in SQL Server. By default, a property named Id becomes the primary key, and string properties map to nvarchar(max).

Books table created

Add a New Column in a Table

Step 1

Add a new property to the model, such as BookLanguage.

Add BookLanguage property

Step 2

Create a new migration.

Add-Migration AddLanguageColumn

Step 3

Apply the migration.

Update-Database

The new column appears in the Books table.

BookLanguage column added

Delete a Column from a Table

Step 1

Remove or comment out the property from the model.

Comment out BookLanguage

Step 2

Create a migration for the removed column.

Add-Migration RemoveLanguageColumn

Step 3

Apply the migration.

Update-Database

The column is removed from the table.

BookLanguage column removed

Change Column Size

Step 1

Add the MaxLength attribute to set the size of a column.

Add MaxLength attribute

Step 2

Create a migration for the size change.

Add-Migration AddColumnSize

Step 3

Apply the migration.

Update-Database

The column now has the configured size.

Column size updated

Make a Column Not Null

Step 1

Add the Required attribute to the property.

Add Required attribute

Step 2

Create a migration.

Add-Migration MakeColumnNotNull

Step 3

Apply the migration.

Update-Database

The column no longer accepts null values.

Column made not null

Delete a Table

Delete a table by removing or commenting out the DbSet from the context file, then add a migration and update the database.

Remove table from context

After applying the migration, the table is removed from SQL Server.

Table removed

Add a Primary Key

In EF Core, a property named Id becomes the primary key automatically. If you want another column to be the primary key, add the Key attribute.

Step 1

Add Key to the column that should be the primary key.

Add Key attribute

Step 2

Create the migration.

Add-Migration AddPrimaryKeyInEmpTable

Step 3

Apply the migration.

Update-Database

The EmpId column is now the primary key.

Primary key updated

Add a Relationship (Foreign Key)

The article adds a Department model with DepartmentId and DepartmentName, then creates a relationship from the employee table.

Department model

Step 1

Add the foreign key property and the navigation property to the employee model. The article notes that if the column name does not match the expected primary key pattern, you should specify it in the ForeignKey attribute.

Employee relationship properties

Step 2

Create a migration for the relationship.

Add-Migration ForeignKey

Step 3

Apply the migration.

Update-Database

The relationship is now present in SQL Server.

Foreign key relationship created

Conclusion

Entity Framework Core Code First makes it straightforward to evolve your database through your C# model classes and migrations. You can add columns, remove columns, change sizes, add constraints, delete tables, and define relationships with a simple workflow.