Entity Framework (13), with .Net Core Code-First Summary

Note: this article is published on 08/13/2024.

After I wrote several articles on this site, I found out it seemed almost for every article, I needed to set up a sample application associated with an entity framework if accessing the database. And, every time, I needed to rewrite the setup process from scratch in order for a new reader to follow along easily. Even for introducing a very simple concept, such as Caching, I needed to spend 80% of the time setting up the sample app, and only 20%  on introducing the Caching concept itself.

Therefore, I think it is better to write a basic model such as entity framework sample for various approaches, and then I can reuse them when needed. I made a list of the series of articles below, I will write them one by one, while the Entity framework overview and concept will be covered in the article (0):

Introduction

This article is a summary of the Entity Frameword Code First approach. The reason that I write this Entity Framework, Code First Approach summary are two

  1. Although from .Net Framework, the Entity Framework introduced three approaches: Code First, Database First and Model First, in the .Net Core, only the Code First Approach is introduced, emphased, while we even cannot find some new published samples or Tutorials on Database First or Model First Approaches.
  2. I realize, Code First approach is a basic one, whatever Database First or Model First, when we use reengineering for Database First to get the database structure, or from model to get database structure in code, the next that we will go to is the exactly same procedure like what Code First Approach does. At this point, we can make details discussion on the Code First Approach, and then convert other approaches into this approach.

This article is a summary or abstract of the Entity Framework Code First Approach. The Content of this article

  • Stage 1, Open a Project
  • Stage 2, Scaffold the Models
  • Stage 3, Create Database
  • Stage 4, Seed the Data
  • Stage 5, ...... others

Stage 1, Open a Project:

As the Step 1 in either

Create a Project, and Run:

Stage 2, Scaffold the Models

First, we setup a data model, such as

We scaffold the Models. The same as in either

MVC

Files created:

Razor

Files created:

The major files created are view files (MVC) or Page Files (Razor), which are

  • Index.cshtml
  • Details.cshtml
  • Create.cshtml
  • Edit.cshtml
  • Delete.cshtml

while the logic are in

  • Controller for MVC
  • Code behind page, for Razor Page, such like:
    • Index.cshtml.cs

At the same time, after scaffolding,

  • A DbContext files created:

  • A Connection String is added into appsettngs.json file
  • The DbContext and the Connection String is registered into Program.cs

Note:

When we first time run the scaffolding, the connection string and the context file will be created automatically. However, if we second time run, or if we have predefined the connection string and DbContext, then the scaffolding will just use the existing one, or the one you chosen.

Stage 3, Create Database

After scaffolding, run the app, it will be compilable and runnable, however, a database error will heppen

--- cannot open database, because it does not exist.

Two ways to Create the Backend Database:

  • using EnsureCreated.  to re-creates the database
  • using migration method

EnsureCreated

This method is to ensures that the database for the context exists.

When a new app is developed, the data model changes frequently. Each time the model changes, the model gets out of sync with the database, so the database needs to be dropped. The next time the app runs, the call to EnsureCreated re-creates the database to match the new data model. The DbInitializer class then runs to seed the new database.

Migration

This approach to keeping the DB in sync with the data model works well until the app needs to be deployed to production. When the app is running in production, it's usually storing data that needs to be maintained. The app can't start with a test DB each time a change is made (such as adding a new column). The EF Core Migrations feature solves this problem by enabling EF Core to update the DB schema instead of creating a new database. Rather than dropping and recreating the database when the data model changes, migrations updates the schema and retains existing data.

EnsureCreated doesn't create a migrations history table and so can't be used with migrations. It's designed for testing or rapid prototyping where the database is dropped and re-created frequently.

The typical migration command

Add-Migration InitialCreate
Update-Database

The first one make a migration code in C# under Migrations folder

Now, if we use EnsureCreated. to create the database:

Then the program is working and linking to database

Stage 4, Seed the Data

Create a new class named SeedData in the Models folder.

Add the seed initializer into program.cs page:

Run, we got the data

Stage 5, ...... Others

So far, we have setup the main frame of the Apps, whatever MVC module or Razor pages (this is the new version of ASP.NET Web Form App). The others are all minor and in details. We may discuss later, but here I just make a list for the possible improvements. They are basically are modifications of pair in Mode/View or data/display.

Somethings including:

  • Details, Create, Edit, Update, Delete 
  • Sort, Filter, Paging, Group
  • Related data strucure
  • Concurrency Handling

as an example, this is the details View sample:

Model Change:

View Change:

Original View Output for Details

New Viw Output for Details:

 

References:


Similar Articles