EntityFramework匿名复合键属性名称冲突

我正在使用EntityFramework 5(或.Net Framework 4.0的4.3)

在我的DbContext对象中,我已经设置了正确的DbSet,并且对象包含彼此正确的引用。 这对我来说并不新鲜,而且事情进展顺利。

现在在这种情况下,我有一些复合键,有时包括表的外键(在这种情况下是对象)。 为此,我在HasKey()OnModelCreating方法上使用HasKey()函数。 当这些属性具有不同的名称时,没有问题,但是当这些属性具有相同的名称时,无法进行迁移。

一个例子:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { // ... modelBuilder.Entity().ToTable("PatientVisits"); modelBuilder.Entity().HasKey(x => new { x.Patient.Code, x.Code }); // ... base.OnModelCreating(modelBuilder); } 

正如您在提供的代码中所看到的,对象PatientVisit具有名为Code的属性,但只要与不同的患者重复该属性,就可以重复此属性。 实体Patient还有一个名为Code的键。

匿名类型不能有两个推断同一名称的属性(显而易见)。 典型的解决方案是命名匿名类型的属性,如下所示:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { // ... modelBuilder.Entity().ToTable("PatientVisits"); modelBuilder.Entity().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 }'. 

我认为你需要做的是给PatientVisit一个新的属性PatientCode 。 哪个是Patient的外键。 例如

  HasRequired(v => v.Patient).WithMany() .HasForeignKey(v => v.PatientCode) 

那你可以做

  modelBuilder.Entity().HasKey(x => new { x.PatientCode, x.Code });