如何首先手动添加导航属性模型

时间:2016-12-27 18:45:45

标签: c# entity-framework navigation-properties ef-model-first

我有一张桌子,上面有书籍,还有一张桌子,上面有模型优先创建的作者。 Books表中有一个指向AuthorID的导航属性 (因为每本书都有作者) 在这里,我试图用值填充表格,当它归结为标量属性时,它是可以的。但是如何为导航属性添加值? 我的导航属性称为AuthorBook enter 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 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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

显然在SaveChanges();

之前

答案 1 :(得分:0)

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();

上述代码将在Book表中创建一条记录,在Author中创建一条记录,在AuthorBook中创建一条记录。您无需手动将代码中的项目添加到AuthorBook,因为EF会为您处理这些内容。