【问题标题】:EntityFramework One to One Assocation实体框架一对一关联
【发布时间】:2015-03-06 16:41:49
【问题描述】:

我正在尝试在 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?

【问题讨论】:

    标签: .net vb.net entity-framework


    【解决方案1】:

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

    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
    

    【讨论】:

    • 你有关于这个主题的资源可以分享吗?
    • 看看这个linkthis
    【解决方案2】:

    对于一对一的关系,其中一个类必须是主体类,而另一个类必须是依赖类。否则 EF 怎么知道首先创建哪个条目。

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

    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属性添加到Bar中的Foo属性:

    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 有一段时间了,希望这段代码能用!

    【讨论】:

    • 第二个变体有一个小问题,Bar 实体中的FooID 不能作为 FK,因为正如您在第一个变体中解释的那样,依赖端的 PK也必须是FK。如果您想使用此变体,请删除 FooId 属性,并仅使用导航属性
    • 你有关于这个主题的资源可以分享吗?
    猜你喜欢
    • 1970-01-01
    • 2016-12-16
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多