如何在与同一其他类型具有其他关系的类型中定义EF多对多关系

时间:2015-12-04 15:40:16

标签: c# ef-code-first entity-framework-6 ef-migrations

这是一个非常简单的问题,有很长的解释,所以请耐心等待。 (我真的会尝试将其保持在最低限度)

好的,这是我提取的样本"产生同样的问题......

public class TestContext : DbContext
{
    public DbSet<TypeA> TypeAs { get; set; }
    public DbSet<TypeB> TypeBees { get; set; }
}

public class TypeA
{
    [Key]
    public int Id { get; set; }
    public int SpecialBId { get; set; }
    public virtual ICollection<TypeB> Bees { get; set; }

    public virtual TypeB SpecialB { get; set; }
}

public class TypeB
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<TypeA> Aaas { get; set; }
}

...所以我启用EF迁移,运行添加迁移,运行更新数据库,我得到了这个......

enter image description here

我期望看到的是一个多对多的联接表,但由于某种原因,第二个&#34; SpecialB&#34;引用导致这打破多对多参考/以某种方式重新定义它。

所以我觉得好吧......也许它只需要一只手所以我在我的上下文中添加了一个onmodel创建......

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TypeA>().HasMany<TypeB>(i => i.Bees);
        modelBuilder.Entity<TypeB>().HasMany<TypeA>(i => i.Aaas);
    }

此时生成迁移不会产生任何效果。

  

那么,我如何让这些关系发挥作用   正确并生成正确的数据库结构?

以防万一...

这是Ef在运行add-migration时为上面的db上下文创建初始迁移时使用所定义类型生成的内容:

public partial class Initial : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.TypeAs",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    SpecialBId = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.TypeBs", t => t.SpecialBId, cascadeDelete: true)
            .Index(t => t.SpecialBId);

        CreateTable(
            "dbo.TypeBs",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    TypeA_Id = c.Int(),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.TypeAs", t => t.TypeA_Id)
            .Index(t => t.TypeA_Id);

    }

    public override void Down()
    {
        DropForeignKey("dbo.TypeAs", "SpecialBId", "dbo.TypeBs");
        DropForeignKey("dbo.TypeBs", "TypeA_Id", "dbo.TypeAs");
        DropIndex("dbo.TypeBs", new[] { "TypeA_Id" });
        DropIndex("dbo.TypeAs", new[] { "SpecialBId" });
        DropTable("dbo.TypeBs");
        DropTable("dbo.TypeAs");
    }
}

1 个答案:

答案 0 :(得分:2)

您需要添加WithMany():

 runtime "oracle:ojdbc6:11.2.0.4.0"