Edwardcho
Edwardcho

Reputation: 138

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

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

actContext.UsersBooks.AddAsync(usersBooks);

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

Upvotes: 1

Views: 493

Answers (2)

AlbertK
AlbertK

Reputation: 13167

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

Upvotes: 3

baruchiro
baruchiro

Reputation: 5801

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.

Upvotes: 1

Related Questions