Entity Framework is saving duplicate values when saving entities with relationship N to N

Asked

Viewed 1,468 times

10

I have an entity called Book that has among other attributes a list of categories. In my model a book can have multiple categories and vice versa, so we have a relationship N to N. EF therefore creates the books table, the category table and one of association between them.

To create a new book in the database I urge an object of type Book, populate the attributes and for each category selected in the form I add a new object of type category the list of categories of the book object just populating the Category Id.

 novoLivro.Categorias.Add(new Categoria(){CategoriaId = selectedId})

I add the book object to my Dbcontext and it saves the book correctly in the database.

However, it saves new records in the category table, which should not, after all all my categories are already in the database and the objects have until the id.

How to make EF understand that it should only save the new book, the associations and not save the categories in the category table as if they were new records?

  • 1

    Thanks guys. Both answers solve my problem. The idea of Attach is interesting because I don’t go to the database just to recover something that was gone before. If I have 20 categories, I would have to make 20 selects when running find.

  • Calm down. If you want to upvote beyond Accept to give me strength, I appreciate!

  • Oops, certainly. But it seems I need more reputation to do that, so I get it, I come back here and I give an upvote. Thanks!

  • Look now. With 10 reputation you can.

  • needs 15 stitches :/

  • 1

    Now yes. Upvoted. Thanks for the help!

Show 1 more comment

2 answers

7


This is because the context intuits that you are creating a new object. If you don’t need to load the categories, you can use hollow objects attached to the context just to save the new entity, more or less like this:

var categoria = new Categoria { CategoriaId = selectedId };
context.Categorias.Attach(categoria);
novoLivro.Categorias.Add(categoria);

If you want to load the category record, use the @Jbruni solution.

2

You are creating a new category with new Categoria.

You need to pass the existing Category object as parameter:

novoLivro.Categorias.Add(categoriasContext.Categorias.Find(selectedId))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.