Relational DB - Getting Data including Data from Other Entities (Repository Pattern)
Let's see how we can get data from a primary entity that has reference to other entities
Implementation
Creating an Application
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
Adding Relationship
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 develop
jin-co.tistory.com
For better demonstration, I have created three entities
You can download the seed data for testing
Adding Repository Pattern
Application Architecture - Repository with Service
An Interface is a kind of contract that specifies what the application needs. Let's see how we can use an interface with the repository pattern. Project Configurations Creating a Project with MVC Pattern Server Architecture - Distributing Projects Server S
jin-co.tistory.com
Adding Methods in the Interface
Add methods to the interface to get data from each entity
Implementing Interface
Go to the repository and implement the methods
Updating the Controller
Add additional endpoints for added entities. To specify the path use parenthesis and put a path in it as a string
[HttpGet("targets")]
Run
Move to the API folder
cd /API
And run the app
dotnet watch
You will see added endpoints right away like below if you are using Swagger
Open each and try
Getting Referenced Data from the Primary Entity
As you can see, referenced data in the primary entity show a 'null' value. We need an additional step to show their data
Add EntityFrameworCore namespace in the repository file
using Microsoft.EntityFrameworkCore;
Then add the 'Include' method to include data from foreign entities
public List<Item> GetItems()
{
return _context.Items
.Include(i => i.ItemTarget)
.Include(i => i.ItemType)
.ToList();
}
After the update, you will see that the actual data comes back not the null values
We have seen how we can get data from an entity that has reference to other entities.