EntityFramework Anonymous Composite Key Name Conflict

I am using EntityFramework 5 (or 4.3 for .Net Framework 4.0)

In my DbContext object, I already set the correct DbSets, and the objects contain the correct links to each other. This is not new to me, and everything works well.

Now in this case, I have compound keys, which sometimes include the foreign key of the table (or the object in this case). To do this, I use the HasKey<>() function in the HasKey<>() method for DbContext. When these properties have different names, there is no problem, but when these properties have the same name, migration cannot be performed.

Example:

 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); } 

As you can see in the presented code, the PatientVisit object has a property called Code, but this property can be repeated as long as it is repeated with another patient. Essence The patient also has a key defined as a "Code".

An anonymous type cannot have two properties, invoking the same name (obviously). A typical solution would be to name anonymous type properties as follows:

 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); } 

But at the same time, when I try to add a migration, this error message is called.

 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 }'. 
+7
source share
1 answer

I think what you need to do here is to give PatientVisit new PatientCode property. Which would be a Patient foreign key. for example

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

Then you can do

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

All Articles