EntityFramework 5(または.Net Framework 4.0の場合は4.3)を使用しています
私のDbContextオブジェクトでは、すでに正しいDbSetを設定しており、オブジェクトには相互への適切な参照が含まれています。これは私にとって目新しいことではなく、物事はうまく機能しています。
この場合、テーブル(この場合はオブジェクト)の外部キーを含む複合キーがいくつかあります。このために、DbContextHasKey<>()
のメソッドの関数を使用します。OnModelCreating
これらのプロパティの名前が異なる場合は問題ありませんが、同じ名前の場合は移行できません。
例:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
modelBuilder.Entity<PatientVisit>().ToTable("PatientVisits");
modelBuilder.Entity<PatientVisit>().HasKey(x =>
new { x.Patient.Code, x.Code });
// ...
base.OnModelCreating(modelBuilder);
}
提供されたコードでわかるように、オブジェクトPatientVisitにはCodeという名前のプロパティがありますが、このプロパティは、別の患者で繰り返される限り繰り返すことができます。エンティティPatientには、Codeという名前のキーが定義されています。
匿名タイプは、同じ名前を推測する2つのプロパティを持つことはできません(明らかです)。一般的な解決策は、匿名タイプのプロパティに次のように名前を付けることです。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
modelBuilder.Entity<PatientVisit>().ToTable("PatientVisits");
modelBuilder.Entity<PatientVisit>().HasKey(x =>
new { PatientCode = x.Patient.Code, VisitCode = x.Code });
// ...
base.OnModelCreating(modelBuilder);
}
しかし、これを行うと、移行を追加しようとすると、このエラーメッセージがスローされます。
The properties expression 'x => new <>f__AnonymousType3`2(PatientCode
= x.Patient.Code, VisitCode = x.Code)' is not valid. The expression
should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t)
t.MyProperty'. When specifying multiple properties use an anonymous
type: C#: 't => new { t.MyProperty1, t.MyProperty2 }'
VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.