[ Entity Framework 5.0 RC で Code First DbContext を使用する]
2 つのナビゲーション プロパティ / 2 つの外部キーを持つエンティティ
public class Compositon
{
public string Id { get; set; }
public string SimpletonId { get; set; }
[ForeignKey("SimpletonId")]
public Simpleton Simpleton { get; set; }
public string CompanitonId { get; set; }
[ForeignKey("CompanitonId")]
public Companiton Companiton { get; set; }
}
最初のパス - 空のデータベースへの SaveChanges の動作
var composition = new Compositon();
compositon.Id = "UniquePrimaryKey";
var simpleton = new Simpleton();
// This foreign key does not exist in database yet
simpleton.Id = "Simpleton1";
composition.Simpleton = simpleton;
var companiton = new Companiton();
companiton.Id = "SomeOther1";
composition.Companiton = companiton;
// Repositor references the DbContext
Repositor.Compositons.Add(composition);
Repositor.SaveChanges();
2 番目のパス - 既存の子の外部キーが親の障害につながる
var composition = new Compositon();
compositon.Id = "AnotherUniquePrimaryKey";
var simpleton = new Simpleton();
// This foreign key already exists in database
simpleton.Id = "Simpleton1";
composition.Simpleton = simpleton;
var companiton = new Companiton();
companiton.Id = "SomeOther2";
composition.Companiton = companiton;
Repositor.Compositons.Add(composition);
Repositor.SaveChanges();
DbUpdateException: An error occurred while updating the entries.
これらの親クラスをデータベースに保存できるようにする必要があります。これらの親クラスには、既に保存されているナビゲーション プロパティが含まれている場合がありますが、一意であるためです。この子の主キーの競合から親を保存するにはどうすればよいですか?