Entity Framework 6 导航 属性 Collections

Entity Framework 6 Navigation Property Collections

我正在 VB.NET 使用 entity framework 版本 6.1.1 和 sql 服务器 2008 开发数据库第一个应用程序。我有一些 link 很多的纯连接表两个表之间的许多关系。我的实体未被跟踪。

以下是我正在使用的 类(从 EF tt 文件生成)的基本示例:

Public Class Part
    Public Property id As Long
    Public Property name As String
    Public Overridable Property CarModels As ICollection(Of CarModel) = New HashSet(Of CarModel)
End Class

Public Class CarModel
    Public Property id As Long
    Public Property name As String
    Public Overridable Property Parts As ICollection(Of Part) = New HashSet(Of Part)
End Class

当我更新实体的字段时,我设置值,然后包含如下代码:

obj.Name = "New Name"
context.Entry(obj).State = EntityState.Modified
context.SaveChanges

这将按我的预期将名称值保存到数据库中。我的问题是尝试将新的 CarModel 添加到现有零件,或从零件中删除现有的 CarModel。我尝试了几件事,但没有找到解决方案。这是我的代码示例:

Dim p As Part = context.Parts.where(Function(it) it.id.equals(1)).first 'Part I am working with
Dim c As CarModel = context.CarModels.where(Function(it) it.id.equals(1)).first 'Car Model I want to associate to the part
p.CarModels.Add(c) 'Add the Car Model to the part collection

context.Entry(p).State = EntityState.Modified

context.SaveChanges

没有抛出错误。当我调试时,CarModel 被添加到 Part.CarModel collection。但是,更改不会提交到数据库。如果我添加一个新部分并使用类似的代码它可以工作,但我无法添加或删除现有的 collection 并让它提交到数据库。

我已经 6 年没用过 VB,所以这可能不完全正确,但这会让您大致了解它的工作原理。

Dim p As Part = context.Parts.where(Function(it) it.id.equals(1)).first 'Part I am working with
Dim c As CarModel = context.CarModels.where(Function(it) it.id.equals(1)).first 'Car Model I want to associate to the part

Dim newPart As Part = New Part()
newPart.id = p.id
newPart.name = p.name
newPart.CarModels = c

context.Add(p)

context.SaveChanges()

我看了一下上下文本身,这一行在上下文的构造函数中:

Configuration.AutoDetectChangesEnabled = False

这就是导致我出现特殊问题的原因。我在某处读到(在我找到该行之后),建议不要将 set AutoDetectChangesEnabled 设置为 false,除非有一个很长的 运行 过程,在这种情况下,在该过程完成后将其设置回 true。从上下文构造函数中删除该行解决了我的问题。