Mapping navigation property to a different name of the database's foreign key (Entity Framework 5)
Posted on: August 29, 2013
In some rare case I had to map an entity to a column which doesn't have the same name. What can you do if the property name of your entity is not the same as the table field? Let's take a simple exemple of an entity "Muscle" which has many "Exercise" linked. A single exercise is related to a single required muscle.
modelBuilder .Entity<Exercise>() .HasRequired(b => b.Muscle) .WithMany(m => m.ExerciseRelated) .IsIndependent() .Map(p=>p.MapKey(m => m.MuscleID, "Muscle_ID") ;
In the example above, you can see that Exercise marks its Muscle property to be required and set the Muscle entity to have multiple Exercise. If you want to not have both side to link to each other, you can let the WithMany parameter to nothing, which would mean that only Exercise has a Muscle association, and not Muscle to Exercises.
The next keywork in the Linq statement is IsIndependent which specify to Entity Framework that the foreign key is not the one you expect to and that you will map to another name. But, this keywork doesn't exist anymore with Entity Framework 5.
Consolidation of IsIndependent in the Code First relationship API. When configuring relationships in Feature CTP5 the IsIndependent method was used to identify that the relationship did not have a foreign key property exposed in the object model. This is now done by calling the Map method. HasForeignKey is still used for relationships where the foreign key property is exposed in the object model.
So the code above with Entity Framework 5.
modelBuilder .Entity<Exercise>() .HasRequired(b => b.Muscle) .WithMany(m => m.ExerciseRelated) .Map(p=>p.MapKey("Muscle___ID")) ;
So instead of using the default navigation name which should have been "Muscle_ID" (Entity name + primary key with underscore between), Entity Framework will use "Muscle_ID".
Beware of the HasColumnName which is for property name that is not the same which is nothing related with association. The map keyword shines for association only.
modelBuilder .Entity<Exercise>() .Property(x => x.Muscle) .HasColumnName("MuscleX");