【发布时间】:2013-11-28 12:26:06
【问题描述】:
假设我有 2 个具有多对一关系的表:Book -> Author。作者可以有多本书。因此,Book 实体具有 Author 和 AuthorId 导航属性。
例如 Author 表包含一行:AuthorName。仅当名称唯一时,我才想插入新作者。
那么,我该怎么做:
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;
}
那么,我怎样才能将 AuthorId 分配给 book,而不是将新的 Author 插入到数据库中(如果它已经存在)?
【问题讨论】:
-
代码优先吗? ID是DB生成的吗?
-
book.Author = authorFromDatabase;呢? -
@sprinter252,先是数据库,在数据库中生成AuthorId。
-
我会选择这个:book.Author = authorFromDatabase ?? new Author("作者姓名");
-
那么您的问题是名称的唯一性吗?
标签: c# database entity-framework foreign-keys