EntityFramework Core Many to Many

In this post, we going to look how to use many to many relationship at entityframewok core 6.0.

Definition

Many to many relationship to explain by example, we can express it like this; every movie has more than one actor, every actor has more than one movie well as

Intro

Let's start by installing the following ef core packages.

Install-Package Microsoft.EntityFrameworkCore

Install-Package Microsoft.EntityFrameworkCore.Tools

Firstly, We define two entity called Post and Tag . Every post could has more than one Tag, every tag could has more than one Post.

First Solution

Post.cs

Tag.cs

In this state, first migration will create then ef core will create table called PostTag automatically but we cant access as class to this table.

Alternatively We can define the relationship using fluent api.

Common table as manuel and FluentApi usage (Second Solution)

The difference of the method below between above is that we create the indermate table, so we can check on table.

PostTag.cs

Post.cs

Tag.cs

FluentApi
Crud operations (Create - Update - Delete)

Create

Add to Exist Record

Update

At Many to Many relationships could has more than one update cases. For example we update post entity and the payload are content, title etc. tags are string array. In this case, we could happen this cases:

  • Exist tags could come again.
  • All tags can remove.
  • New tags could added. (at the tags table)

The three case can be at same time therefore all cases can be done in single code block. Firstly we're remove all tags of the entity to be updated. Then we add it if exist in tags table, otherwise we create a new tag.

Delete

We could remove the tags of post without any restrictions thus if we remove one record in tags table, removed from all posts associated with that tag. This operation is CascadeDelete.

Gönderinin sonuna geldik, okuduğunuz için teşekkürler 🙂 başka bir gönderide görüşmek üzere.

You may also like...

Leave a Reply

Your email address will not be published.

English