简体   繁体   中英

How to rename column in one-to-many relation in EF Core?

I have a League class which contains Teams property, which is a collection of teams as shown below:

public class LeagueEntity
{
    [Key]
    public int LeagueId { get; set; }
    ...
    [Required]
    public ICollection<TeamEntity> Teams { get; set; }
}


public class TeamEntity
{
    [Key]
    public int TeamId { get; set; }
    [Required]
    [MaxLength(100)]
    public string Name { get; set; }
    [Required]
    [MaxLength(10)]
    [Column(TypeName = "varchar(10)")]
    public string Code { get; set; }
    [Required]
    [MaxLength(300)]
    public string Logo { get; set; }
    [Required]
    [MaxLength(100)]
    public string Country { get; set; }
    [Required]
    public string IsNational { get; set; }
    [Required]
    public int Founded { get; set; }
    [Required]
    public VenueEntity Venue { get; set; }
}

When i update the database, two tables are created - Leagues and Teams. In Teams table i have a column which is foreign key pointing to the correct league, where the team belongs to. The column is named "LeagueEntityLeagueId". How to rename it?

Make the foreign key explicit as follows:

public class TeamEntity
{
    [Key]
    public int TeamId { get; set; }

    [ForeignKey("League")]
    public int LeagueId { get; set; } //  You can give the whatever name you want

    .........

    public LeagueEntity League {get; set;}

}

If you don't want explicit foreign key and navigation property then you can do as follows:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<LeagueEntity>().HasMany(l => l.Teams).WithOne().HasForeignKey("LeagueId");

}

In TeamEntity Table add the following property

  public int LeagueId { get; set; }
  public virtual LeagueEntity LeagueEntity { get; set; }

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