我正在使用 EntityFramework 5(或 4.3 for .Net Framework 4.0)
在我的 DbContext 对象中,我已经设置了正确的 DbSet,并且这些对象包含对彼此的正确引用。这对我来说并不新鲜,而且运行良好。
现在在这种情况下,我有一些复合键,有时包括表(或在这种情况下为对象)的外键。为此,我使用 HasKey<>()
OnModelCreating
上的函数DbContext 的方法。当这些属性的名称不同时,没有问题,但是当这些属性具有相同的名称时,就无法进行迁移。
一个例子:
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 的键。
匿名类型不能有两个推断相同名称的属性(显而易见)。典型的解决方案是像这样命名匿名类型的属性:
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 }'.
最佳答案
我认为您在这里需要做的是为 PatientVisit
提供一个新属性 PatientCode
。这将是 Patient
的外键。例如
HasRequired<PatientVisit>(v => v.Patient).WithMany()
.HasForeignKey(v => v.PatientCode)
然后你可以做
modelBuilder.Entity<PatientVisit>().HasKey(x =>
new { x.PatientCode, x.Code });
关于c# - EntityFramework 匿名复合键属性名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13933569/