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

c# entity-framework-core

Question

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?

1
0
3/16/2020 12:08:19 PM

Popular Answer

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

}
3
3/16/2020 12:21:27 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow