我对DbSet.Add(entity)
的理解是所有相关实体都应该被标记为已添加,因此会导致在SaveChanges时插入。但是,我正在处理的代码似乎必须手动设置context.Entry().State
作为新实体的单一导航属性。
var library = new Library();
library.Sections.Add(new Section {Name="Fiction"});
library.Sections.Add(new Section {Name="NonFiction"});
library.Sections.Add(new Section {Name="Reference"});
library.Librarian = new Librarian {Name="Conan"};
context.Libraries.Add(library);
context.SaveChanges()
在上面的简化代码中,不应该插入3个新的Section实体和新的Librarian实体吗?我所看到的是,如果我没有手动将图书馆员实体标记为EntityState.Added,则没有插入,但是所有部分都将被插入。