【发布时间】:2015-01-12 23:06:18
【问题描述】:
我正在使用实体框架版本 6.1.1 和 sql server 2008 在 VB.NET 中开发数据库优先应用程序。我有一些纯连接表,它们链接两个表之间的多对多关系。我的实体未被追踪。
以下是我正在使用的类(从 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
这将按我的预期将 Name 值保存到数据库中。我的问题是尝试将新的 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 集合中。但是,更改不会提交到数据库。如果我添加一个新部件并使用类似的代码,它可以工作,但我无法从现有集合中添加或删除并将其提交到数据库。
【问题讨论】: