如何为 table 与 Entity Framework 的多对多关系添加条目

How to add entries for many to many relation table with Entity Framework

我有一个包含三个表的数据库:WordIdiomWordIdiom,存储这两个表之间的多对多关系。 WordItem 仅包含 WordIdiom 表的外键。

之后,我创建了基于数据库的实体模型。我已经用相关内容填充了两个表,现在我想在这些表之间添加交叉链接。

所以,我写了这段代码:

using (var db = new IdiomsDictionaryEntities())
{
    var allIdioms = from idiom in db.Idioms select idiom;

    foreach (var idiom in allIdioms)
    {
        string[] words = idiom.IdiomText.Split(new[] { " ", "-" }, StringSplitOptions.None);

        foreach (var word in words)
        {
            var wordItem = db.Words.SingleOrDefault(exWord => exWord.WordString.ToLower().Equals(word));
            if (wordItem == null)
            {
                Console.WriteLine("Idiom: " + idiom.IdiomText + ", missing word: " + word);
                continue;
            }

            idiom.Words.Add(wordItem);

            db.SaveChanges();
        }
    }
}

但是当我 运行 这段代码时,出现以下错误:

An unhandled exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll
Additional information: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

内在异常:

Unable to update the EntitySet 'WordIdiomMatch' because it has a DefiningQuery and no element exists in the element to support the current operation.`

因为这是我第一次使用 Entity Framework,所以我真的不知道如何解决这个问题。我尝试将 [ForeignKey()] 属性 添加到 Entity Framework 模型,但可能做错了。我还尝试为 WordIdiom 添加一个主键,但它会阻止更多的事情,因为在这种情况下我什至无法将项目添加到 WordIdiom 表。

首先,我看到您有 2 个 add() 用于相同的目的。 是错误的。想象一下它在数据库中会是什么样子:

wordItem.Idioms.Add(idiom);

现在 X 和 Y 被 link link table 编辑为 "X-Y" 记录。

idiom.Words.Add(wordItem);

现在...它会创建另一个记录 link 这些 "Y-X" 是没用的,如果已经有一个 "X-Y" 记录那么 X 是link用这条记录变成了 Y,反之亦然。

而且我会说...通常 link table 的主键是它包含的两个外键的组合,所以双加无论如何都会崩溃。

在@KerryRandolph 和@AntoinePelletier 的帮助下,我已经解决了这些问题

我试图使用 Pure Join Table 更新从多对多关系派生的实体 - 这意味着除了外键之外不允许使用其他列。 如果您将 Primary Key 列添加到 Join Table,您将失去所有 entity framework 的优势,并且必须手动执行插入操作。

正确的解决方案是更改数据库上的连接 table 以创建包含两个外部 ID 列的 PK。