简体   繁体   English

如何使用 Entity Framework 7 通过流畅的 API 指定外键列名?

[英]How to specify foreign key column name, via fluent API, with Entity Framework 7?

I'm trying out Entity Framework 7, coming from EF6.我正在尝试来自 EF6 的实体框架 7。 I'm working with an existing database, manually writing the model configurations (not using the reverse engineered schema via EF) because I already had a project with all the necessary entity classes.我正在使用现有数据库,手动编写模型配置(不通过 EF 使用反向工程架构),因为我已经有一个包含所有必要实体类的项目。 I'm trying to figure out how to specify the column name for a HasOne relationship.我想弄清楚如何为HasOne关系指定列名。 The querying being generated is using the incorrect name for the property used in HasOne .正在生成的查询对HasOne使用的属性使用了错误的名称。 Here's my configuration for this particular model ...这是我对这个特定模型的配置......

modelBuilder.Entity<Season>(season =>
{
    season.ForNpgsqlToTable("season");

    season.HasKey(m => m.Id);
    season.Property(m => m.Id)
          .HasColumnName("id");
    season.Property(m => m.Name)
          .HasColumnName("name");
    season.Property(m => m.Slug)
          .HasColumnName("slug");
    season.Property(m => m.DateEnd)
          .HasColumnName("date_end");
    season.Property(m => m.DateStart)
          .HasColumnName("date_start");
    season.Property(m => m.DateCreated)
          .HasColumnName("date_created");
    season.HasOne(m => m.Division)
          .WithMany();
});

When a query for this entity is dispatched, every column is correct except the foreign key one, which is just using the default naming generation of "DivisionId", when in reality the column needs to just be "division".当对该实体的查询被调度时,除了外键之外的每一列都是正确的,它只是使用“DivisionId”的默认命名生成,而实际上该列只需要是“division”。

How can I specify the column name using fluent API?如何使用 fluent API 指定列名?

In my experience it seems that EF 7 is not ready to map class reference to foreign keys yet, I thought the following would work but not so far:根据我的经验,EF 7 似乎还没有准备好将类引用映射到外键,我认为以下方法可行,但目前还不行:

season.Property<Division>("Division")
                .ForSqlServerHasColumnName("division");

Having said that, the recommended approach will be to map the foreign key property that support the class reference and us:e it to configure the mapping column话虽如此,推荐的方法是映射支持类引用的外键属性,并使用它来配置映射列

season.Property(e => e.DivisionId)
                 .ForSqlServerHasColumnName("division");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM