1

Foo のテーブルと Bar のテーブルを含む EF Code First モデルがあります。これは多対多の関係であるため、EF は FooBars というジャンクション テーブルを生成しました。

CreateTable(
    "dbo.FooBar",
    c => new
        {
            Foo_Id = c.Int(nullable: false),
            Bar_Id = c.Int(nullable: false),
        })
    .PrimaryKey(t => new { t.Foo_Id, t.Bar_Id })
    .ForeignKey("dbo.Foos", t => t.Foo_Id, cascadeDelete: true)
    .ForeignKey("dbo.Bars", t => t.Bar_Id, cascadeDelete: true)             
    .Index(t => t.Foo_Id)
    .Index(t => t.Bar_Id);

大丈夫だ。ここで、モデルにいくつかの変更を加え、移行を追加しました。Foo エンティティには、いくつかの追加の string および int プロパティが含まれるようになりましたが、関係などに変更はありません。ただし、何らかの理由で、EF はジャンクション テーブルを BarFoos と呼ぶ必要があると主張し、元の FooBars テーブルを削除したいと考えています。

 DropForeignKey("dbo.FooBars", "Foo_Id", "dbo.Foos");
 DropForeignKey("dbo.FooBars", "Bar_Id", "dbo.Bars");
 DropIndex("dbo.Foobars", new[] { "Foo_Id" });
 DropIndex("dbo.FooBars", new[] { "Bar_Id" });

 CreateTable(
      "dbo.BarFoos",
           c => new
                {
                    Bar_Id = c.Int(nullable: false),
                    Foo_Id = c.Int(nullable: false),
                })
 .PrimaryKey(t => new { t.Bar_Id, t.Foo_Id })
 .ForeignKey("dbo.Bars", t => t.Bar_Id, cascadeDelete: true)
 .ForeignKey("dbo.Foos", t => t.Foo_Id, cascadeDelete: true)
 .Index(t => t.Bar_Id)
 .Index(t => t.Foo_Id);

 DropTable("dbo.FooBars");

もちろん、すべてのレコードを FooBars から BarFoos にコピーすることもできますが、それは非常に厄介であり、モデルに変更を加えてこの特定の移行を再生成するときに、引き続き行う必要があります。なぜ EF はジャンクション テーブルが突然逆になるべきだと主張するのですか? これを回避するために何かできますか?

4

1 に答える 1

1

以前にこれが発生しました-解決策は見つかりませんでしたが、回避策はFluent APIでテーブル名を強制することでした. 例えば:

modelBuilder.Entity(Of User)() _ 
.HasMany(Function(u) u.Roles) _ 
.WithMany(Function(r) r.Users) _ 
.Map(Function(u) u.MapRightKey("Role_RoleID").MapLeftKey("User_UserID").ToTable("UserRoles"))

(C#、質問の言語に合わせて):

modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(u => u.MapRightKey("Role_RoleID").MapLeftKey("User_UserID").ToTable("UserRoles"));
于 2015-04-29T14:28:30.143 に答える