C# Entity Framework Adding to Many-To-Many Table

.net c# entity-framework-6


Is this a good practice to insert into a many-to-many table?

user = new User
            Id = userId,
            UserName = username,
            FirstName = firstName,
            LastName = lastName,
            UsersBooks = new List<UsersBooks>()

        book = new Book
            Title = "randomTitle2",
            Genre = "randomGenre2",
            UsersBooks = new List<UsersBooks>()

        usersBooks = new UsersBooks
            User = user,
            Book = book

And at last I add it to the context


So I have this UsersBooks collection in each of the classes - user & book. One user can have many books and one book can be acquired by many users(copies of Harry Poter, let's say). So should I every time create a new

  • usersBook and add it while passing the user and the book each time? Because I see that after that the book is added to it's according table, which is correct. Maybe I am asking if there is a better way in terms of most used by experienced developers
2/5/2019 9:46:00 AM

Accepted Answer

With EF6 you have two options:

1) Since EF6 supports many-to-many relation out-of-the-box you can go with that feature (that noted in the comment by vasily.sib).

Pros: your models and code look more cleaner without an excess model (UsersBooks)

Cons: it is not flexible way. In the future you may need to add additional properties to the relation table. This approach doesn't allow it

2) Handle many-to-many relation with two one-to-many realtions (like you did)

Pros: you can add any additional properties to this relation. It is a flexible approach

Cons: you code always should work with one more model (UsersBooks)

So, if you handle a simple scenario enough, then you can go with the first approach. Otherwise you need to consider the second.

BTW, currently, EF core doesn't support many-to-many relation

2/5/2019 11:47:50 AM

Popular Answer

You don't need to insert directly into the UsersBooks table.

Once you update the users list in book, or the books list in user, the relationship (in UsersBooks) will update automatically.

Actually, you don't need to declare a UsersBooks model for the many-to-many relationship. If you declare ICollection<User> in your Book Code First model, and also declare ICollection<Book> in the User model, the UsersBooks table will create in the database automatically by Entity Framework.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow