Reader small image

You're reading from  Web API Development with ASP.NET Core 8

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781804610954
Edition1st Edition
Concepts
Right arrow
Author (1)
Xiaodi Yan
Xiaodi Yan
author image
Xiaodi Yan

Xiaodi Yan is a seasoned software engineer with a proven track record in the IT industry. Since 2015, he has been awarded Microsoft MVP, showcasing his dedication to and expertise in .NET, AI, DevOps, and cloud computing. He is also a Microsoft Certified Trainer (MCT), Azure Solutions Architect Expert, and LinkedIn Learning instructor. Xiaodi often presents at conferences and user groups, leveraging his extensive experience to engage and inspire audiences. Based in Wellington, New Zealand, he spearheads the Wellington .NET User Group, fostering a vibrant community of like-minded professionals. Connect with Xiaodi on LinkedIn to stay updated on his latest insights.
Read more about Xiaodi Yan

Right arrow

Data Access in ASP.NET Core (Part 2 – Entity Relationships)

In Chapter 5, we introduced the fundamentals of Entity Framework Core (EF Core), including how to create a DbContext class and how to use it to access data.

You can recap the basic concepts of relationships in Chapter 1, in the Defining the Relationships between Resources section, where we introduced relationships between resources. For example, in a blog system, a post has a collection of comments, and a user has a collection of posts. In an invoice system, an invoice has a collection of invoice items, and an invoice item belongs to an invoice. An invoice also has a contact, which can have one or more contact persons and can have one address.

In this chapter, we will continue to explore the features of EF Core. We will learn how to manage relationships between entities using Fluent APIs. Finally, we will discuss how to implement CRUD operations for entities with relationships.

We will cover the following topics...

Technical requirements

The code examples in this chapter can be found at https://github.com/PacktPublishing/Web-API-Development-with-ASP.NET-Core-8/tree/main/samples/chapter6. You can use VS 2022 or VS Code to open the solutions.

You are expected to have basic knowledge of Structured Query Language (SQL) queries and Language-Integrated Query (LINQ). If you are not familiar with them, you can refer to the following resources:

Understanding one-to-many relationships

One-to-many relationships are the most common relationships in a relational database. They are also called parent-child (children) relationships. For example, an invoice has a collection of invoice items. In this section, we will learn how to configure a one-to-many relationship in EF Core and how to implement CRUD operations for entities with a one-to-many relationship.

Let us continue to use the invoice sample application. You can find the sample code of the EfCoreRelationshipsDemo project in the chapter6 folder. If you would like to test the code following the book, you can continue to work on the BasicEfCoreDemo project. Note that the InvoiceDbContext class has been renamed SampleDbContext in the sample code.

Next, let us update the Invoice class and create an InvoiceItem class, then define the one-to-many relationship between them.

One-to-many configuration

To demonstrate a one-to-many relationship, we need to add a new class...

Understanding one-to-one relationships

A one-to-one relationship means that one entity has a relationship with only one entity of another type. For example, a bicycle requires one lock, which can only be used for that particular bicycle. Similarly, a person is only allowed to possess one driver’s license, which is designated for their use only. In our sample code, a Contact entity has only one Address entity, and an Address entity belongs to only one Contact entity. In the previous section, you learned how to configure a one-to-many relationship using the HasOne()/WithMany() and HasMany()/WithOne() methods. In this section, you will learn how to configure a one-to-one relationship using the HasOne() and WithOne() methods.

One-to-one configuration

In a one-to-one relationship, both sides have a reference navigation property. Technically, both sides have equal positions. However, to explicitly configure the relationship, we need to specify which side is the dependent side...

Understanding many-to-many relationships

A many-to-many relationship is when an entity can be associated with multiple entities and vice versa. For example, a movie can have many actors, and an actor can act in many movies; a post can have many tags, and a tag can have many posts; a student can enroll in many courses, and a course can have many students, and so on. In this section, we will introduce how to configure a many-to-many relationship in EF Core.

Many-to-many configuration

In a many-to-many relationship, we need to define a collection navigation property on both sides. Here is an example of a many-to-many relationship between a Movie entity and an Actor entity:

public class Movie{
    public Guid Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string? Description { get; set; }
    public int ReleaseYear { get; set; }
    public List...

Understanding owned entities

In the previous sections, we have learned some relationships are optional, but some are required. For example, a post can exist without a category, but a student ID card cannot exist without a student. For the latter, we can say a student owns an ID card. Similarly, a contact owns an address. We can also find some examples of one-to-many relationships. For example, an invoice owns many invoice items because an invoice item cannot exist without an invoice. In this section, we will introduce the concept of owned entities.

Owned entity types are entity types that are part of the owner and cannot exist without the owner. You can use common one-to-one or one-to-many relationships to model the owned entities, but EF Core provides a more convenient way called owned entity types. You can use the OwnsOne() or OwnsMany() method to define owned entity types, instead of using the HasOne() or HasMany() method. For example, to configure the InvoiceItem entity as an...

Summary

In this comprehensive chapter, we delved into modeling relationships between entities in EF Core. We explored various common relationship types, including one-to-one, one-to-many, and many-to-many relationships. We learned how to configure these relationships using essential methods such as HasOne()/WithMany(), HasMany()/WithOne(), and HasMany()/WithMany(). To broaden our understanding, we also explored configuring owned entity types using the OwnsOne()/WithOwner() and OwnsMany/WithOwner() methods.

To effectively operate on entities with relationships, we explained how to implement CRUD operations for each type of relationship. Particularly, we explained cascading delete operations, ensuring data integrity and efficient management of related entities.

The concepts learned in this chapter will help you model relationships between entities in your ASP.NET Core applications. In the next chapter, we will learn about some advanced topics of EF Core, such as concurrency control...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Web API Development with ASP.NET Core 8
Published in: Apr 2024Publisher: PacktISBN-13: 9781804610954
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Xiaodi Yan

Xiaodi Yan is a seasoned software engineer with a proven track record in the IT industry. Since 2015, he has been awarded Microsoft MVP, showcasing his dedication to and expertise in .NET, AI, DevOps, and cloud computing. He is also a Microsoft Certified Trainer (MCT), Azure Solutions Architect Expert, and LinkedIn Learning instructor. Xiaodi often presents at conferences and user groups, leveraging his extensive experience to engage and inspire audiences. Based in Wellington, New Zealand, he spearheads the Wellington .NET User Group, fostering a vibrant community of like-minded professionals. Connect with Xiaodi on LinkedIn to stay updated on his latest insights.
Read more about Xiaodi Yan