【问题标题】:EF Core 2.0 OwnsOne column prefixEF Core 2.0 OwnersOne 列前缀
【发布时间】:2018-01-10 12:18:36
【问题描述】:

使用OwnsOne映射复杂类型时,sql列名以属性名为前缀。是否可以在映射中指定前缀名称?

这是我的映射:

e.OwnsOne(x => x.Attributes, cb =>
{
    cb.OwnsOne(a => a.Supplier);
});

我希望 sql 列以“Attr_”而不是“Attributes_”为前缀。这可能吗?

【问题讨论】:

  • 目前这个约定是hardcoded。您可以向github.com/aspnet/EntityFrameworkCore/issues 发布功能请求。解决方法是为所有属性(包括嵌套拥有类型的属性)显式配置列名。
  • @Ivan Stoev,你知道显式映射的语法吗?刚刚在 IEntityTypeConfiguration 文件中尝试过:builder.Property(x=>x.Address.Postcode).HasColumnName("PostCode")。但它会抛出异常 ArgumentException: The expression 'ea => ea.Address.Postcode' is not a valid property expression。该表达式应表示属性访问:'t => t.MyProperty'。参数名称:propertyAccessExpression
  • @Jafin 必须通过相应的OwnsOne builder 操作参数来完成。例如.OwnsOne(e => e.Address, cb => { cb.Property(e => e.Postcode).HasColumnName("Postcode"); });
  • 您还可以使用数据注释来覆盖列名。例如使用 [Column("Supplier")] 注释将使用它作为不带前缀的列名。属性Column 存在于命名空间System.ComponentModel.DataAnnotations.Schema 中。此方法的优点是对于实体类文件是本地的,因此添加其他属性的其他开发人员可以通过注意现有属性来注意到需要覆盖列名。

标签: ef-core-2.0


【解决方案1】:

您可以编写一个扩展方法来覆盖所有列的名称;

   public static void WithPrefix<T, R>(this OwnedNavigationBuilder<T, R> builder, string prefix) where T:class where R:class
   {
      foreach (var p in builder.OwnedEntityType.GetProperties())
         p.SetColumnName($"{prefix}{p.Name}");
   }

   .OwnsOne(e => e.Address, cb => cb.WithPrefix(""));

【讨论】:

    【解决方案2】:

    Ivan Stoev 对问题 cmets 的回答:

    必须通过相应的OwnsOne builder 操作参数来完成。例如.OwnsOne(e =&gt; e.Address, cb =&gt; { cb.Property(e =&gt; e.Postcode).HasColumnName("Postcode"); });

    (将其设为社区 wiki,只需将问题标记为已回答。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2018-06-02
      • 2018-05-01
      • 2020-04-19
      相关资源
      最近更新 更多