20. Many-to-Many Relationships in Entity Framework Core

SdĂ­let
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

Komentáƙe • 57

  • @odamuser
    @odamuser Pƙed 3 lety +3

    Man, you saved my life! Clean, easy, perfect! You're awesome, man!! Thank u!

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety +1

      You are welcome. Thanks for watching! 🙏

  • @ExpatTraderFX
    @ExpatTraderFX Pƙed rokem

    Bravo "shume bukur" explanation

  • @erikipsen1682
    @erikipsen1682 Pƙed rokem

    Nice, simple and strait to the case! Thanks for uploading this video 🙂

  • @TheSamuelssmelo
    @TheSamuelssmelo Pƙed 3 lety +2

    You are an amazing teacher. Great content!!

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety +1

      Thank you soooo much Samuel

  • @renatocarvalho6059
    @renatocarvalho6059 Pƙed 2 lety

    Amazingly useful, clean and clear! Thank you very much!

  • @LafsGaming
    @LafsGaming Pƙed 2 lety

    You made me understand this concept... Thanks for that ✌

  • @sherlockholmes1121
    @sherlockholmes1121 Pƙed 20 dny

    Very Very useful thanks

  • @yoannhenry6361
    @yoannhenry6361 Pƙed rokem

    Thanks a lot : It helps me in minutes !! Great Job!!

  • @RohitSharma-vq2gn
    @RohitSharma-vq2gn Pƙed 3 lety +1

    This is extremely lucid explanation of both Fluent Api usage and EF Core. Great work, Ervis :)

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety

      Thank you so much for your feedback, Rohit! â˜ș

  • @fieryscorpion
    @fieryscorpion Pƙed 3 lety

    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!

  • @LeartBajrami-co1gn
    @LeartBajrami-co1gn Pƙed 2 měsĂ­ci +1

    valid

  • @arohawrami8132
    @arohawrami8132 Pƙed 2 lety

    Thanks a lot Ervis. It is a very useful tutorial.

    • @DotNetHow
      @DotNetHow  Pƙed 2 lety

      Thanks for watching. I am glad you found them useful.

  • @motoviagensmg4400
    @motoviagensmg4400 Pƙed 2 lety

    Excellent explanation, very concise.

  • @JustasNomeika
    @JustasNomeika Pƙed rokem

    Thanks for the video.
    Should I create instances of all - Book, Author and Author_Book objects? and then add them to the database?

  • @eliumoraes
    @eliumoraes Pƙed 2 lety

    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.

    • @DotNetHow
      @DotNetHow  Pƙed 2 lety

      Add a mew property -> Add-Migration -> Update-Database

  • @EnGamology
    @EnGamology Pƙed 3 lety +1

    This one is the best

  • @imermamani2205
    @imermamani2205 Pƙed 2 lety

    this is very very easy to learn

  • @youtube.com-handle
    @youtube.com-handle Pƙed 2 lety

    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

  • @Engineer2261
    @Engineer2261 Pƙed 2 měsĂ­ci

    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?

    • @DotNetHow
      @DotNetHow  Pƙed měsĂ­cem

      In the joining table you can add a column, isPrimaryAuthor: boolean

  • @asfandalikhan6269
    @asfandalikhan6269 Pƙed 3 lety

    Thanks bro

  • @SharpCoder
    @SharpCoder Pƙed 2 lety

    How it use on practice. Related entities does not updates

  • @pritomsarkar2963
    @pritomsarkar2963 Pƙed 3 lety +1

    Awesome Sir. But Please try to Create a dynamically multitenant simple web application.

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety

      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

  • @pourianayeb1063
    @pourianayeb1063 Pƙed 3 lety +1

    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?

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety +3

      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

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety +1

      I used the default conventions in One-to-Many, but wanted to show that you can customize relations (table names, columns) using Fluent API

    • @pourianayeb1063
      @pourianayeb1063 Pƙed 3 lety +1

      @@DotNetHow just got it, thanks 😊

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety +1

      @@pourianayeb1063 you are welcome

  • @Spirittism
    @Spirittism Pƙed 2 lety

    wished you did some interaction with the db using linq

  • @sobrelaroca2701
    @sobrelaroca2701 Pƙed 2 lety

    Where is the create? update?

  • @semajxocliw
    @semajxocliw Pƙed 2 lety

    ef core should be able to handle many-to-many automatically as of 5.0

    • @DotNetHow
      @DotNetHow  Pƙed 2 lety +1

      That is right. I just wanted to show that it is customisable

    • @qwertz3813
      @qwertz3813 Pƙed 2 lety

      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

  • @robxlift
    @robxlift Pƙed 3 lety

    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.

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety

      Can you provide additional info, like what are your models, what did you write inside OnModelCreating?

    • @robxlift
      @robxlift Pƙed 3 lety

      @@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; }

    • @robxlift
      @robxlift Pƙed 3 lety

      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; }

    • @DotNetHow
      @DotNetHow  Pƙed 3 lety

      @@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.

    • @robxlift
      @robxlift Pƙed 3 lety

      @@DotNetHow i delete old project and make new one , but same error but with new models

  • @Elyeslahmar
    @Elyeslahmar Pƙed rokem

    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 });***/