본문 바로가기

Backend/.NET

Adding Relation to DB

반응형

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!

 

728x90
반응형