How to add navigation property manually model first

246 views Asked by At

I have a table with books and a table with authors created by model-first. There's a navigation property in Books table pointing to AuthorID (because each book has an author) here i'm trying to fill in the tables with values and it's okay when it comes down to scalar properties. But how to add a value to navigation property? My navigation property is called AuthorBookenter image description here

 Book book1 = new Book();
 Author author1 = new Author();
author1.Surname = "Dickens";
 author1.Name = "Charles";
 db.AuthorSet.Add(author1);`
hbook1.Title = "Great Expectations";
book1.Genre = "Novel"
db.BookSet.Add(book1);
 db.SaveChanges();

'

2

There are 2 answers

6
Z . On

try something like this:

var rel = new AuthorBook { Book = book1, Author = author1 };
book1.AuthorBook.Add(rel);

that obviously goes before SaveChanges();

9
CodingYoshi On
Book book1 = new Book();
book1.Title = "Great Expectations";
book1.Genre = "Novel"

// Add 1 or more authors
Author author1 = new Author();
author1.Surname = "Dickens";
author1.Name = "Charles";

// AuthorBook better be a collection since a book can have 1 or many authors
book1.AuthorBook.Add(author1); 

db.BookSet.Add(book1);
db.SaveChanges();

The above code will create one record in Book table, 1 in Author and one in AuthorBook. You do not need to manually add an item in code to AuthorBook since EF will take care of that for you.