EF 试图插入未更改的实体

EF trying to insert Unchanged entities

编辑:知道了!感谢大家的帮助 :) 我在最后发布了 "solution",尽管我不知道它是否会对任何人有所帮助,但主要是由于我的设计不当..


我在尝试 .SaveChanges()

时收到 DbUpdateException

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.

InnerException 是:

Violation of PRIMARY KEY constraint « PK_ProduitDepot_1 » ... Cannot insert duplicate key in object Produit-Depot ..

这是我用来查看应保存哪些实体的一些代码:

 Dim allEntries = MyContext.ChangeTracker.Entries
    Dim unchangedEntities As New Dictionary(Of Object, EntityState)

    For Each entry As DbEntityEntry In allEntries
        Dim NotUnchangedEntity = entry.Entity
        If MyContext.Entry(NotUnchangedEntity).State <> EntityState.Unchanged Then
            unchangedEntities.Add(entry.Entity, MyContext.Entry(entry.Entity).State)
        End If
    Next

    MyContext.Database.Log = AddressOf Console.WriteLine
    context.SaveChanges()

我在调试模式下看到 unchangedEntities 是空的。

关于 EF,我是否遗漏了什么?我不明白如果我的上下文缓存中只有未更改的实体,为什么会有任何 SQL 执行...

tableProduit-Depot 是一个具有 * 到 * 关系的联结 table,因此 EF 尚未创建 class table(这是数据库第一个项目)

如果有任何不清楚的地方,请告诉我。

解决方案

有趣的部分:

正如 Ivan Stoev 指出的那样,由于错误消息是关于一个结点 table(没有 class 与之关联,因为 EF 在生成我的模型时没有创建任何结点),这些实体未在 ChangeTracker.Entries 中列出。这就是为什么我相信所有实体都处于未更改状态。

可能无用的部分:

我使用 Context.Person.Include("Cars.Wheels")(虚构的名称,但你明白了)通过添加解决了我的问题。我曾经只有 Context.MyEntity.Include("Cars"),后来以某种方式手动分配我的汽车的 Wheels 导航 属性,使用 FK。这就是问题的来源。