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

9

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 N relationship for N. The EF therefore creates the books table, the category table and one of association between them.

To create a new book in the database I instantiate 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 Id of the Category.

 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 do you make EF understand that it should only save the new book associations and not save the categories in the category table as if they were new records?

    
asked by anonymous 12.02.2014 / 22:21

2 answers

7

This is because the context intuits that you are creating a new object. If you do not need to load the categories, you can use hollow objects attached to the context just to save the new entity, something 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.

    
12.02.2014 / 22:41
2

You are creating a new category with new Categoria .

You need to pass the existing Category object as a parameter:

novoLivro.Categorias.Add(categoriasContext.Categorias.Find(selectedId))
    
12.02.2014 / 22:30