实体框架一对一协会

时间:2015-03-06 16:41:49

标签: .net vb.net entity-framework

我试图在EF Code First中使用Conventions over Configuration来定义0..1 - 1关联......但是我遇到了错误:

  

无法确定之间关联的主要结束   类型'Bar'和'Foo'。这种关联的主要目的必须是   使用关系流畅的API或数据显式配置   注释

我的POCO课程如下:

Public Class Foo
    Public Property ID As Integer
    Public Property Description As String
    Public Overridable Property Bar As Bar
End Class

Public Class Bar
    Public Property ID As Integer
    Public Property FooID As Integer
    Public Property Description As String
    Public Overridable Property Foo As Foo
End Class

有谁知道我哪里出错了?

以下是我正在使用的一些资源:

https://msdn.microsoft.com/en-us/data/jj713564

http://www.entityframeworktutorial.net/entity-relationships.aspx

How to tell EntityFramework 5.0 that there's a one-to-one association between two entities?

2 个答案:

答案 0 :(得分:1)

通过一对一的关系,其中一个类必须是主体,另一个必须依赖。否则,EF将如何知道首先创建哪个条目。

有两种方法可以解决这个问题。将ForeignKey属性添加到ID类的Foo属性:

Public Class Foo
    <Key(), ForeignKey("Foo")>
    Public Property ID As Integer
    Public Property Description As String
    Public Overridable Property Bar As Bar
End Class

或者将Required属性添加到Foo中的Bar媒体资源中:

Public Class Bar
    Public Property ID As Integer
    Public Property FooID As Integer
    Public Property Description As String
    <Required()>
    Public Overridable Property Foo As Foo
End Class

PS已经有一段时间了,因为我已经完成了VB,希望这段代码有效!

答案 1 :(得分:1)

我同意@DavidG选择解决您问题的解决方案,但我猜您在一对一关系中的主要终点是Foo实体。因此,在第一个变体中,如果您想使用FK属性,则必须以这种方式配置Bar实体(它是dependend ent):

Public Class Bar
   <Key(), ForeignKey("Foo")>
   Public Property FooID As Integer
   Public Property Description As String
   Public Overridable Property Foo As Foo
End Class

现在,关于第二个变体(使用Required数据注释),应删除FooId FK属性,因为正如我之前所说,在一对一关系中,PK属性在依赖端也必须是FK。因此,如果您只想使用此变体,请使用导航属性:

 Public Class Bar
   Public Property ID As Integer
   Public Property Description As String
   <Required()>
   Public Overridable Property Foo As Foo
End Class