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?