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?
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.
– Eduardo Bottcher
Calm down. If you want to upvote beyond Accept to give me strength, I appreciate!
– Leonel Sanches da Silva
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!
– Eduardo Bottcher
Look now. With 10 reputation you can.
– Leonel Sanches da Silva
needs 15 stitches :/
– Eduardo Bottcher
Now yes. Upvoted. Thanks for the help!
– Eduardo Bottcher