实体框架代码首先创建意外的表和关系

时间:2015-05-21 15:56:24

标签: entity-framework

使用EntityFramework 6.1.3,我得到了以下内容

  public class RacesContext:DbContext
{
    public DbSet<Race> Races { get; set; }
    public DbSet<Sailboat> Sailboats { get; set; }
    public DbSet<VenueParticipation> VenueParticipations { get; set; }

}


public class Crew
{
    public int CrewId { get; set; }
    public string Name { get; set; }
}

public class Sailboat
{
    [Key]
    public int SailboatId { get; set; }
    public string Name { get; set; }
    public string Skipper { get; set; }
    public virtual ICollection<Crew> BoatCrew { get; set; }
}

public class VenueParticipation
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Sailboat> Boats { get; set; }
    public virtual ICollection<Race> Races { get; set; }
}

public class Race
{
    [Key]
    public  int  RaceId { get; set; }
    public string Venue { get; set; }
    public DateTime Occurs { get; set; }

}

EF创建Creates the Crews表,其中包含正确的PK和FK,如我所料。但是以意想不到的方式创建了Races Sailboats,VenueParticipations表格。帆船获得了预期的PK但意外的FK VenueParticipation_Id和Races一样。我期待VenueParticipations表能够让其他人获得FK,从而允许他们建立多对多的关系。我确信我在这里遗漏了一些东西。任何建议都会很棒。

1 个答案:

答案 0 :(得分:1)

您可以使用正确的FK配置连接表VenueParticipationSailboat,VenueParticipationRace,也可以使用流畅的API:

modelBuilder.Entity<VenueParticipation>() 
.HasMany(t => t.Sailboats) 
.WithMany(t => t.VenueParticipations) 
.Map(m => 
{ 
    m.ToTable("VenueParticipationSailboat"); 
    m.MapLeftKey("VenueParticipationID"); 
    m.MapRightKey("SailboatID"); 
});

https://msdn.microsoft.com/en-us/data/jj591620.aspx#ManyToMany