实体框架6导航属性集合

时间:2015-01-09 22:15:35

标签: vb.net entity-framework-6

我正在使用实体框架版本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集合中。但是,更改不会提交到数据库。如果我添加一个新的部件并使用类似的代码,它可以工作,但我无法添加或删除现有的集合并让它提交到数据库。

2 个答案:

答案 0 :(得分:0)

我还没有在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()

答案 1 :(得分:0)

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

Configuration.AutoDetectChangesEnabled = False

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