【问题标题】:EF 4 Code First: How can I modify naming conventions for generated junction tables?EF 4 Code First:如何修改生成的联结表的命名约定?
【发布时间】:2011-03-23 11:35:10
【问题描述】:

我正在与现有数据库集成,因此我希望我的 EF4 Code First 代码生成的表遵守已经存在的表命名约定。

现有约定是单数实体名称,前缀为小写“t”(例如tProduct),并在连接表中加入下划线(例如tProduct_tOffer)。

我已经使用下面的代码通过所有“标准”表实现了这一点。在我的DbContext 我有:

protected override void OnModelCreating(ModelBuilder modelBuilder) {
    modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
    modelBuilder.Conventions.Add<TableNamePrefixConvention>();
    base.OnModelCreating(modelBuilder);
}

下面的类将“t”添加到表名中:

public class TableNamePrefixConvention : IConfigurationConvention<Type, EntityTypeConfiguration> {
    public void Apply(Type typeInfo, Func<EntityTypeConfiguration> configuration) {
        configuration().ToTable("t" + typeInfo.Name);
    }
}

但是,当生成 junction 表时,它不遵守这些约定。所以我现在在表格列表中有这种东西:

tOffer
tProduct
ProductOffers

在这种情况下,ProductOffers 应命名为 tProduct_tOffer。如何强制生成的联结表符合我的命名风格?

更新:正如 Ladislav 在下面正确猜到的,我使用的是 CTP5。

【问题讨论】:

  • 自定义约定不是最终代码首次发布的一部分,因此您可能正在使用 CTP5。安装 RC 或 RTW(最终)版本后将无法使用。
  • 很高兴知道。那我该怎么办?

标签: c# database-design asp.net-mvc-3 entity-framework-4 ef-code-first


【解决方案1】:

正如我在评论中指出的,自定义约定在 RC 版本中不可用,并且在 RTW 中也不可用 (official announcement)。

您必须手动映射:

modelBuilder.Entity<Offer>()
    .HasMany(o => o.Products)
    .WithMany(p => p.Offers)
    .Map(m => m.ToTable("tProduct_Offer"));

代码 sn-p 是 RC 版本。 CTP5 对IsIndependent() 使用了更多步骤,但在 RC 中已将其删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-11
    • 2015-07-08
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多