如何在数据库中的EF Code First中配置现有数据库中的类之间的关系?

时间:2014-07-25 20:39:54

标签: vb.net entity-framework fluent entity-framework-6.1

我阅读了Julie Lerman的一些帖子,并在这里试图弄清楚如何配置2个实体之间的关系。我使用EF Code First从现有的数据库生成类,我无法控制并且已经拥有大量数据。在一个表中,PostIdguid,而PostRowIDPK。当我修改类以尝试获得关系时,我最终得到错误Invalid object name 'dbo.be_PostTagbe_Posts'.大多数(如果不是所有)示例似乎都处理Code First而不是DB中的Code First。如何映射两个类之间的关系?或者我需要第三张表来映射关系?

我也看了一下流畅的api并且走得很远:

modelBuilder.Entity(Of be_Posts)().HasMany(Function(a) 
a.be_PostTag).WithMany().Map(Function(x)
x.MapLeftKey("PostID")x.MapRightKey("PostID") 'Don't know what to do next

当发生这种情况时,我正在尝试使用Include语法。我添加了2个ICollection属性,但我怀疑因为db偏离EF约定,这就是为什么EF无法弄清楚这种关系。

Partial Public Class be_Posts

    <Key>
    Public Property PostRowID As Integer

    Public Property BlogID As Guid

    Public Property PostID As Guid

    'Other Stuff

    Public Property be_PostTag As ICollection(Of be_PostTag)

End Class

并且

Partial Public Class be_PostTag
    <Key>
    Public Property PostTagID As Integer

    Public Property BlogID As Guid

    Public Property PostID As Guid

    'Other stuff

    Public Property be_Posts As ICollection(Of be_Posts)

End Class

包括:

  Using db As New BetterBlogContext
     post = db.be_Posts.OrderByDescending(Function(x)
     x.DateCreated).Include("be_PostTag").Where(Function(p) p.PostRowID
     = id).FirstOrDefault
   End Using

1 个答案:

答案 0 :(得分:0)

没有使用Fluent API就搞清楚了。添加2个ICollection属性后,我不得不手动添加所需的表Entity Framework以及相应的2列来处理关系。使用SQL命令复制所需的数据,一切正常。

相关问题