In Entity Framework code first, When I want to create a mapping for a normal one-to-many foreign key, I use
HasRequired(a=>a.County)
.WithMay(b=>b.Cities)
.HasForeignKey(a=>a.CountCode);
Now when I instead try to create a one-to-one-mapping, it will become something like this:
HasRequired(a=>a.County)
.WithOptional(b=>b.ConnectedCounty)
.Map(a=>a.MapKey("CountyCode"));
Why do I have to use a string like CountyCode in this expression? Is there a way to create the mapping not having strings, just linq expressions?
The reason is that you are not supposed to use this when you define one-to-one relationship because by using this you will get back to defining one-to-many relationship in the database. EF uses real one-to-one relationship only when FK in dependent entity is also its PK. That is the only situation when you can be sure that principal entity will never be referenced by more than one dependent entity (because EF doesn’t support database unique keys).
If you use your code you will define separate FK and it will “work” but there will be no automatically created unique key on the column in the database.