【问题标题】:Entity Framework 6 Navigation Property CollectionsEntity Framework 6 导航属性集合
【发布时间】: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 集合中。但是,更改不会提交到数据库。如果我添加一个新部件并使用类似的代码,它可以工作,但我无法从现有集合中添加或删除并将其提交到数据库。

【问题讨论】:

    标签: vb.net entity-framework-6


    【解决方案1】:

    我已经 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()
    

    【讨论】:

    • 感谢您的建议。我试了一下,得到了类似的结果。问题是由我的上下文中的设置引起的,在我的回答中进行了解释。
    【解决方案2】:

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

    Configuration.AutoDetectChangesEnabled = False
    

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

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 2015-03-29
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      相关资源
      最近更新 更多