Let's see how we can get data from a primary entity that has reference to other entities
Implementation
Creating an Application
Adding Relationship
For better demonstration, I have created three entities
You can download the seed data for testing
Adding Repository Pattern
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.
'Backend > .NET' 카테고리의 다른 글
Relational DB - Getting Data Asynchronous (0) | 2023.04.16 |
---|---|
Relational DB - Getting Data including Data from Other Entities (Generic Repository Pattern) (0) | 2023.04.15 |
Application Architecture - Generic Repository (0) | 2023.04.09 |
Application Architecture - Repository with Service (0) | 2023.04.07 |
Adding Configurations When Creating a Database (2) | 2023.03.31 |