简体   繁体   中英

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

I'm trying out Entity Framework 7, coming from EF6. 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. I'm trying to figure out how to specify the column name for a HasOne relationship. The querying being generated is using the incorrect name for the property used in 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".

How can I specify the column name using 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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