VB.NET示例实体框架4.2代码优先实体拆分

时间:2011-12-14 03:57:41

标签: vb.net entity-framework entity-framework-4 ef-code-first code-first

实体拆分:一个类,两个或更多个表。

以下是如何在C#中完成的,但我需要在vb.net中使用它 还有一件事:类名和表列匹配,所以我必须能够将其映射出来。

我必须以这种方式工作,因为我现在正在工作的地方是vb.net 唯一商店,而数据库模式是 fubar ,但他们在asp classic,vb.net和asp.net webforms中对数据库进行了很多(数百万)代码直接,现在改变架构是不现实的。< / p>

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Post>()
    .Map(m =>
      {
        m.Properties(p => new { p.Title, p.Content });
        m.ToTable("Posts");
      })
    .Map(m =>
      {
        m.Properties(p => new { p.Photo });
        m.ToTable("PostPhotos");
      });
}

2 个答案:

答案 0 :(得分:3)

这是上述的VB等价物:

    modelBuilder.Entity(Of Post)().Map(Sub(m)
                                          m.Properties(Of Post)(
                                             Function(p) _
                                                New Post With {.Title= p.Title, _
                                                               .Content = p.Content })
                                          m.ToTable("Posts")
                                        End Sub).Map(Sub(m)
                                                       m.Properties(
                                                          Function(p) _
                                                            New Customer With {.Photo = p.Photo})
                                                       m.ToTable("PostPhotos")
                                                     End Sub)

答案 1 :(得分:0)

这是接受答案的正确版本(使用匿名类型)。我希望它会有所帮助...

你确实可以通过点表示法来实现,但代码缩进真的很奇怪。我更喜欢另一种方式:创建 EntityTypeConfiguration

 Public Class PostConfiguration
    Inherits EntityTypeConfiguration(Of Post)

    Public Sub New()

        Map(Sub(m)
                m.Properties(
                   Function(p) _
                      New With {Key p.Title, Key p.Content})
                m.ToTable("Posts")
            End Sub)

        Map(Sub(m)
                m.Properties(
                   Function(p) _
                     New With {Key p.Photo })
                m.ToTable("PostPhotos")
            End Sub)

    End Sub
  End Class

您只需将此配置添加到模型中,如下所示:

  Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder)
        modelBuilder.Configurations.Add(New PostConfiguration)
    End Sub
相关问题