Evan
Evan

Reputation: 167

Entity Framework Code first creates unexpected Tables and Relationships

Using EntityFramework 6.1.3, I've got the following

  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 Creates the Crews table with the proper PK and FK as I would expect. But creates the Races Sailboats, VenueParticipations tables in an unexpected way. Sailboats get's the expected PK but the unexpected FK VenueParticipation_Id as does Races. I was expecting the VenueParticipations table to get FKs to the others allowing a many to many relationship.. I'm sure I'm missing something here. Any advice would be great.

Upvotes: 0

Views: 46

Answers (1)

Steve Greene
Steve Greene

Reputation: 12324

You can either configure the joining tables VenueParticipationSailboat, VenueParticipationRace with the proper FKs or you can use the fluent 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

Upvotes: 1

Related Questions