20. Many-to-Many Relationships in Entity Framework Core
VloĆŸit
- Äas pĆidĂĄn 27. 07. 2024
- ======================================
đ Complete Course: bit.ly/3bJawaZ
đ Github repository: bit.ly/3apXvCH
=====================================
â Many-To-Many Relationship occurs when records in Table A have many linked records in Table B and vice versa.
â In Many-to-Many Relationships, you need to add an additional Entity/Table named Join Entity/Table which stores the relations between Table A and Table B
â Entity Framework Core allows you to use the navigation properties in your model to load related entities
===================================
You can also watch my courses on:
đŻ Udemy: bit.ly/2MaEA5rââââââââ
đŻ LinkedIn Learning: bit.ly/2NJ5PEFââââââââ
đŻ Pluralsight: bit.ly/2EsgjlJââââââââ
===================================
#aspnetcoreâ #webapiâ #csharpâ #onetomanyâ #databaserelationshipsâ #efcoreâ #entityframeworkâ #entityframeworkcore
0:00 - Introduction
1:03 - Adding Author model
2:05 - Adding Book_Author join model
3:33 - Many-to-Many database schema overview
4:34 - Adding navigation properties for Book and Author models
5:17 - Using Fluent API to define model relations
8:45 - Adding a new migration and migration overview
10:25 - Updating database and database relations overview
11:00 - The end
Man, you saved my life! Clean, easy, perfect! You're awesome, man!! Thank u!
You are welcome. Thanks for watching! đ
Bravo "shume bukur" explanation
Thanks
Nice, simple and strait to the case! Thanks for uploading this video đ
You are an amazing teacher. Great content!!
Thank you soooo much Samuel
Amazingly useful, clean and clear! Thank you very much!
Thank you as well
You made me understand this concept... Thanks for that âïž
Very Very useful thanks
Thanks for watching
Thanks a lot : It helps me in minutes !! Great Job!!
This is extremely lucid explanation of both Fluent Api usage and EF Core. Great work, Ervis :)
Thank you so much for your feedback, Rohit! âș
This is amazing. Thank you!
If you add authentication and some clean architecture (eg: Domain Driven Design) to your Udemy course, I'll buy and study it ASAP!
valid
Thanks a lot Ervis. It is a very useful tutorial.
Thanks for watching. I am glad you found them useful.
Excellent explanation, very concise.
Thank you
Thanks for the video.
Should I create instances of all - Book, Author and Author_Book objects? and then add them to the database?
Hello Ervis! Thanks for sharing! I would like to know how can I add more columns in the Books_Authors table like the date to know when the association between this author and book were created.
Add a mew property -> Add-Migration -> Update-Database
This one is the best
Thanks
this is very very easy to learn
Thank you
very useful information, i modified my tables to this fluent api and it migrated successfully.
previously i just added the tables through the OnModelCreating where i joined two tables holding a list of each other into a third table that was named automatically.
still, now i m using the API, lets say that i wanted to add the following scenario
a member have a list of subscriptions, which means the subscriptions have a list of members, thus, Members_Subscriptions table is needed
so i created the tables above with the same configuration; members_subscriptions, now, when i try to insert into the Members_Subscription the API or the context try to insert both the Member and the Subscription into their respective tables, even though i just want to add a new member subscription into the index or joined table. or join them with added properties, i.e. the ending date
Thanks Ervis for the very clear explanation.
How do you add a primary Author constraint to a book? Let's say one book has only one primary author, all the others are considered secondary. Do we need different models for that or can we simply apply it to the joint table?
In the joining table you can add a column, isPrimaryAuthor: boolean
Thanks bro
You are welcome!
How it use on practice. Related entities does not updates
Awesome Sir. But Please try to Create a dynamically multitenant simple web application.
I am building this app about book management. So, you can probably learn the concepts and build that app as your personal project. That would be great
I have 2 questions:
01. How to create composition key for book_authors table, could it be happening by Key attribute or fluent api or maybe both?
02. I'm totally sure I never use fluent api for many-to-many and it works like a charm, why do we need this additional config?
Hello Pouria!
Regarding your questions:
1. Yes, you can use a composition key for the books_authors table. In our case it would be:
modelBuilder.Entity()
.HasKey(t => new { t.AuthorId, t.BookId });
2. You do not need additional FluentAPI code if you want to keep the default columns that the entity framework will generate, but if you want to customize them, then you need to use fluent API. I prefer to use fluent API to set the join table names with underscore "_ ".
In our case, EF Core would generate a table named AuthorBook with two columns, AuthorsId, BooksId
I used the default conventions in One-to-Many, but wanted to show that you can customize relations (table names, columns) using Fluent API
@@DotNetHow just got it, thanks đ
@@pourianayeb1063 you are welcome
wished you did some interaction with the db using linq
Where is the create? update?
ef core should be able to handle many-to-many automatically as of 5.0
That is right. I just wanted to show that it is customisable
But you can customize the key of a pivot if you do it this way.
Example:
modelBuilder.Entity
.HasKey(ma => new { ma.MovieId, ma.ActorId, ma.RoleName });
where RoleName is something new to both of the tables
Introducing FOREIGN KEY constraint 'FK_dbo.VendorDetails_dbo.States_StateID' on table 'VendorDetails' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.
Can you provide additional info, like what are your models, what did you write inside OnModelCreating?
@@DotNetHow Introducing FOREIGN KEY constraint 'FK_StudentCourses_Students_StudentId' on table 'StudentCourses' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasKey(t => new { t.StudentId, t.CourseId});
}
public DbSet Courses { get; set; }
public DbSet Departments { get; set; }
public DbSet Students { get; set; }
public DbSet StudentCourses { get; set; }
Models
in course
public Department Department { get; set; }
public List StudentCourses { get; set; }
in department
public List Students { get; set; }
public List Courses { get; set; }
in student
public Department Department { get; set; }
public List StudentCourses { get; set; }
in studentCourse
public Student Student { get; set; }
public Course Course { get; set; }
@@robxlift I do not see the State anywhere in your models (FK_dbo.VendorDetails_dbo.States_StateID). You need to share the full models, otherwise, it is impossible to offer any help.
@@DotNetHow i delete old project and make new one , but same error but with new models
Je tenais Ă vous remercier pour la vidĂ©o excellente. J'ai cependant remarquĂ© un point Ă corriger concernant la table Book_Author. Il n'est pas nĂ©cessaire d'ajouter une clĂ© primaire distincte. En fait, la clĂ© primaire peut ĂȘtre composĂ©e des clĂ©s Ă©trangĂšres AuthorId et BookId.
Voici la syntaxe correcte à ajouter dans la méthode OnModelCreating de votre classe de contexte DbContext
/*****modelBuilder.Entity().HasKey(r => new{ r.PermissionId,r.RoleId });***/