【问题标题】:Entity Framework Code first creates unexpected Tables and Relationships实体框架代码首先创建意外的表和关系
【发布时间】:2015-05-22 00:14:50
【问题描述】:

使用 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 使用正确的 PK 和 FK 创建 Creates the Crews 表,正如我所期望的那样。但是以一种意想不到的方式创建了 Races Sailboats、VenueParticipations 表。帆船得到了预期的 PK,但意外的 FK VenueParticipation_Id 和 Races 一样。我期待 VenueParticipations 表能够将 FK 传递给其他允许多对多关系的表。我确定我在这里遗漏了一些东西。任何建议都会很棒。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    您可以使用适当的 FK 配置连接表 VenueParticipationSailboat、VenueParticipationRace,也可以使用 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

    【讨论】:

    • 否则,从 VenueParticipation 中删除集合并将它们设置为 FK,具体取决于您要实现的目标 (public int SailboatId { get; set; } [ForeignKey("SailboatId")] public virtual 船{得到;设置;}
    • 谢谢我试图在不使用模型构建器的情况下做到这一点。我可以看到添加 this.Sailboats = new HashSet();比赛 ctor 反之亦然 帆船 ctor 可以解决问题,但我似乎无法填充映射。
    • 你可以在没有模型构建器的情况下完成。 stackoverflow.com/questions/18648600/…
    • 就个人而言,我更喜欢模型构建器。使 POCO 保持清晰并分离关注点。
    • 你说得很好。我只是在评估框架与传统数据优先方法的成熟度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多