2015-01-09 128 views
0

我正在使用实体框架版本6.1.1和sql server 2008在VB.NET中开发数据库第一个应用程序。我有一些连接两个表之间的多对多关系的纯连接表。我的实体没有跟踪。实体框架6导航属性集合

下面是我使用的类(从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集合中。但是,这些更改不会提交给数据库。如果我添加一个新零件并使用它的工作类似代码,但我无法添加或从现有集合中删除并将其提交到数据库。

回答

0

我接过一看语境本身,这条线是在上下文的构造函数:

Configuration.AutoDetectChangesEnabled = False 

那是什么引起了我特别的问题。我读过某处(在找到该行后),建议不要将Set AutoDetectChangesEnabled设置为false,除非有很长的运行过程,并且在该过程完成后将其设置为true。从上下文构造函数中移除该行解决了我的问题。

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() 
+0

感谢您的建议。我试了一下并得到了类似的结果。这个问题是由我的背景下的一个设置引起的,在我的答案中解释。 – ccarter24 2015-01-12 15:07:34