私は、SQLの制約にON DELETE CASCADE
とON UPDATE CASCADE
の両方を適用するためのEntity Frameworkの7で外部キー関係を取得しようとしています。は、どのように私は流暢APIからの外部キーのためにonUpdate設定するのですか?
OnModelCreating
のモデルビルダーを使用している場合、私は削除にカスケードを使用する関係を指定することができますよ。それは私が助けが必要な更新アクションを指定する場所を見つけることです。
class DatabaseContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("...connection string...");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Comment>()
.HasOne(c => c.Post)
.WithMany(p => p.Comments)
.HasForeignKey(c => c.PostName)
.OnDelete(DeleteBehavior.Cascade);
//if you delete the post, delete its comments
modelBuilder.Entity<Comment>().HasKey(c => new { c.Number, c.PostName });
}
}
class Post
{
[Required, Key, StringLength(100)]
public string Name { get; set; }
public string Contents { get; set; }
public List<Comment> Comments { get; set; }
}
class Comment
{
public int Number { get; set; }
[Required]
public Post Post { get; set; }
[Required, StringLength(100)]
public string PostName { get; set; }
public string Contents { get; set; }
}
私はAdd-Migration First
を実行し、これはUp
方法のために生成されたコードです:
は、ここに私のサンプルモデルのコードです。
migrationBuilder.CreateTable(
name: "Post",
columns: table => new
{
Name = table.Column<string>(nullable: false),
Contents = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Post", x => x.Name);
});
migrationBuilder.CreateTable(
name: "Comment",
columns: table => new
{
Number = table.Column<int>(nullable: false),
PostName = table.Column<string>(nullable: false),
Contents = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Comment", x => new { x.Number, x.PostName });
table.ForeignKey(
name: "FK_Comment_Post_PostName",
column: x => x.PostName,
principalTable: "Post",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade
// ,onUpdate: ReferentialAction.Cascade
);
});
最後のパラメータはコメントアウトされています。私はこれを後で手動で追加しました。私は、行のコメントを解除した場合、作成されたSQLテーブルはがON UPDATE CASCADE
を適用していません。
今私は手動で更新カスケードのサポートを追加するために、私の移行ファイルを変更する必要があります。移行ファイルが作成されたとき、私は移行エンジンは私にとってonUpdate: ReferentialAction.Cascade
を追加することができます流暢API内の方法はありますか?
Searching through the github codeいくつか興味深い結果が得られています。また、移行ファイルを手動で編集するとどうなるかわかりました。 CSharpMigrationOperationGenerator
クラスで
、発電機は私が必要な値を書き込むための能力を持っている必要がありますので、onUpdate:
を書き込むためAddForeignKeyOperation
has a sectionを扱うGenerate
方法。どのように私はそれを引き起こすのですか?
、私はOnModelCreating
に外部キーの作成後、次を追加しました:
modelBuilder.Entity<Comment>()
.Property(p => p.PostName)
.ValueGeneratedOnAddOrUpdate();
移行は、このコードなしで作成された移行と同一であっ作成し、したがって、結果のSQLテーブルに変更はありません。
これは移行に何の相違も生じませんでした。私は私のポストに詳細を追加しました。 – gunr2171