【问题标题】:How to assign entity Id to another entity without inserting first entity into database in Entity Framework, C#?如何将实体 ID 分配给另一个实体而不将第一个实体插入到实体框架中的数据库中,C#?
【发布时间】: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


【解决方案1】:

设置.AuthorId 属性不会在数据库中创建新的Author - 怎么可能?您实际上并没有构建一个新的Author 对象并将其添加到您的DbContext。从你给我们看的内容来看,if(authorFromDatabase == null) 似乎总是解析为True。您是否调试过代码以确保 else 块被执行过?

您可能应该展示更多代码,例如您的AuthorBook 实体类以及您的getAuthorFromDbByName(...) 方法实现以及您在哪里实例化您的DbContext 实例。

【讨论】:

  • 抱歉误导你,设置 .AuthorId 对我有用)只是遗漏了一些东西。一切正常,无论如何谢谢,在你的回答之后,我再次检查了一切并解决了我的问题。
  • 而 if(authorFromDatabase == null) 并不总是解析为 True。因为我已经在数据库中有一些条目,我想更新它们
【解决方案2】:

如果是关于独特性,我会这样做:

// some code
newBook.Author = CreateOrGetAuthor("The Name");
// more code

private Author CreateOrGetAuthor(string authorName)
{
    var author = _context.Authors.SingleOrDefault(a => a.Name.Equals(authorName, StringComparison.CurrentCultureIgnoreCase));
    if (author == null)
    {
        author = new Author();
        author.Name = authorName;
    }
    return author; 
}

现在这取决于您是否围绕这两个调用使用事务。如果没有,您必须先调用 _context.SaveChanges() 并在 CreateOrGetAuthor 中返回作者。否则它不会有 ID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多