Entity framework makes adding a relationship between tables easy. Let's see how it is done.
Creating an Application
First, let's create a .NET application.
How to create a .NET web-API application (tistory.com)
How to create .NET web-API
Setting up development tools When working with .NET, we need tools to create a web application. We can download them in the link below.다. .NET | Free. Cross-platform. Open Source. (microsoft.com) .NET | Free. Cross-platform. Open Source. .NET is a develo
jin-co.tistory.com
Creating Entities
For this example, I have created two tables as below.
To better organize our project, let's create a folder to hold the entities first.
Primary Entity
Add a new C# class in the folder
Then add attributes for the entity. Note that the primary entity that is referring to another entity must have the id of the entity (works as a foreign key) and the entity itself that it is referring to. The Entity Framework uses this information to create a relation when migrating
Foreign Entity
Add another C# class in the folder
Add attributes for the entity.
Creating DB
Package Set up
Working with SQLite in .NET (Code first)
There are two ways of using the Entity Framework to connect a database to a project. One way is to create the database first which is called the database first approach and the other, of course, is to write code first which is called the code first approac
jin-co.tistory.com
Context Set up
Working with SQLite in .NET (Code first)
There are two ways of using the Entity Framework to connect a database to a project. One way is to create the database first which is called the database first approach and the other, of course, is to write code first which is called the code first approac
jin-co.tistory.com
Context Update
Before running any migration command, we have to add all the entities to the context file like below.
Now Set up the service in the 'Program.cs' file and run the migration and it is done!
'Backend > .NET' 카테고리의 다른 글
.NET - Cleaning Up Program File: Service Extension Method (0) | 2023.03.08 |
---|---|
How to create .NET web-API (1) | 2023.03.02 |
Auto Migration and Data Seeding (1) | 2023.03.01 |
Server Architecture - Distributing Projects (1) | 2023.03.01 |
Working with SQLite in .NET (Code first) (1) | 2023.03.01 |