【问题标题】:VB.NET Sample Entity Framework 4.2 Code First Entity SplittingVB.NET 示例实体框架 4.2 代码优先实体拆分
【发布时间】:2011-12-14 03:57:40
【问题描述】:

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

这是它在 C# 中的完成方式,但我需要让它在 vb.net 中工作。
还有一件事:类名和表列匹配,所以我也必须能够映射出来。

我必须让它以这种方式工作,因为我现在工作的地方是 vb.net only 商店,并且数据库架构是 fubar,但是他们在 asp classic、vb.net 和 asp.net 网络表单中对数据库直接编写了这么多(数百万)行代码,因此现在更改架构实际上是不可能的。

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");
      });
}

【问题讨论】:

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


    【解决方案1】:

    这是上面的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)
    

    【讨论】:

    • 数据库表真的需要 2 个类吗?我的意思是帖子和照片。用匿名类是不可能的吗?
    【解决方案2】:

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

    您确实可以通过点表示法来做到这一点,但是代码缩进真的很奇怪。我更喜欢另一种方式:创建一个 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      • 2014-05-23
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多