Suppose I have 2 tables with many to one relationship: Book -> Author. Author can have multiple books. So, Book entity has Author and AuthorId navigation properties.
For example Author table contains one row: AuthorName. I want to insert new Author only if the name is unique.
So, what I do:
var book = new Book();
var authorFromDatabase = getAuthorFromDbByName("author name");
if(authorFromDatabase == null)
{
// insert new author if it is not already in the database
book.Author = new Author("author name");
}
else
{
// how to assign AuthorId to book so that it will not add new Author to the db??
// the following line inserts new author into the db
book.AuthorId = authorFromDatabase .AuthorId;
}
So, how can I assign AuthorId to book and not insert a new Author into the db if it's already there?
book.Author = authorFromDatabase;
? – Adriano Repetti