D.B
D.B

Reputation: 4289

Add data to a many-to-many relationship using Entity Framework

How can I Add data to a many-to-many relationship using Entity Framework? I have got a problem when I try to add one article with its related categories (see diagram), but the thing is that the categories already exist in the Categories Table, i don't need to create them again. When I use EF Method: _ctx.Articles.Add(newArticle), It generates insert sentences to categories table and duplicate my rows. Basically, I only need to add data to Article table and the reference table CategoryArticles. Add method, add rows to Article table (ok) plus Category table (wrong step) plus CategoryArticles table (ok).Any Idea How can I avoid to add these rows in my category table again.? Appreciate any help.

EDIT: I AM USING AUTOMAPER FOR FILLING AN ARRAY OF CATEGORIES... I DO NOT IF MAYBE DOING IT ON THAT WAY I AM CREATING NEW OBJECTS. IT IS THE CODE:

List<CategoriesViewModel> categoriesViewModel = article.CategoriesViewModel.Where(c => c.IsSelected).ToList();
List<Category> selectedCategories = Mapper.Map<List<CategoriesViewModel>, List<Category>>(categoriesViewModel);    

newArticle.Categories = selectedCategories;

_ctx.Articles.Add(newArticle)

This is the relational model

enter image description here

Upvotes: 1

Views: 1780

Answers (2)

D.B
D.B

Reputation: 4289

Thanks to @Robert McKee, the way to solve the problem is to fetch the categories directly from the database, that way the entity framework automatically recognise these categories when the main entity is being saved, avoiding duplicate them.

Upvotes: 2

Robert McKee
Robert McKee

Reputation: 21487

Many to Many relationships hide the cross reference table in EF. The relationship model shouldn't show the CategoryArticles table at all. The Articles table should have a "Categories" navigation property. Just add a category to it, and save.

enter image description here

Upvotes: 0

Related Questions