我有一个名为WidgetCollection的类。它具有公开List(Of Widget)类型的Items属性和SelectedWidget属性。我希望EF按照以下方式构建数据库:
我猜问题是EF无法理解双向关系,并且我找不到将其指向正确方向的方法。以下是示例代码,欢迎提出所有建议!
- 在我的Widgets表中添加一个WidgetCollection_Id属性,以指定每个widget所在的WidgetCollection
- 在我的WidgetCollection表中添加一个SelectedWidget_Id属性,以指定所选Widget是哪一个
- 从WidgetCollection.Id到Widget.WidgetCollection_Id添加一对多的关系
- 从Widget.Id到WidgetCollection.SelectedWidget_Id添加一个1对0或1的关系
并且内部异常为:System.Data.Entity.Infrastructure.DbUpdateException occurred HResult=-2146233087 Message=An error occurred while saving entities that do not expose foreign key > properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.
如果不将WidgetCollect.SelectedWidget赋值,则可以防止此错误。Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
我猜问题是EF无法理解双向关系,并且我找不到将其指向正确方向的方法。以下是示例代码,欢迎提出所有建议!
Public Class Widget
Private miId As Integer
Public Property Id As Integer
Get
Return miId
End Get
Set(value As Integer)
miId = value
End Set
End Property
Private msName As String
Public Property Name As String
Get
Return msName
End Get
Set(value As String)
msName = value
End Set
End Property
End Class
Public Class WidgetCollection
Private miId As Integer
Public Property Id As Integer
Get
Return miId
End Get
Set(value As Integer)
miId = value
End Set
End Property
Private msName As String
Public Property Name As String
Get
Return msName
End Get
Set(value As String)
msName = value
End Set
End Property
Private moSelectedWidget
Public Property SelectedWidget As Widget
Get
Return moSelectedWidget
End Get
Set(value As Widget)
moSelectedWidget = value
End Set
End Property
Private moWidgets As New List(Of Widget)
Public Property Widgets As List(Of Widget)
Get
Return moWidgets
End Get
Set(value As List(Of Widget))
moWidgets = value
End Set
End Property
End Class
Public Class MyContext
Inherits DbContext
Public Property Widgets As DbSet(Of Widget)
Public Property WidgetCollections As DbSet(Of WidgetCollection)
End Class
Class Application
Public Sub New()
Database.DefaultConnectionFactory = New SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", "", "Data Source=\EFtest.sdf")
Database.SetInitializer(New DropCreateDatabaseIfModelChanges(Of MyContext))
Dim oContext = New MyContext
Dim oWidgetA = New Widget With {.Name = "Widget A"}
Dim oWidgetB = New Widget With {.Name = "Widget A"}
Dim oWidgetCollection = New WidgetCollection With {.Name = "My widget collection"}
oWidgetCollection.Widgets.Add(oWidgetA)
oWidgetCollection.Widgets.Add(oWidgetB)
oWidgetCollection.SelectedWidget = oWidgetA 'Removing this line prevents error
oContext.WidgetCollections.Add(oWidgetCollection)
oContext.SaveChanges()
End Sub
End Class