Ran into a small problem today, where I had two classes referring to one another using EF 4.1 Code First. Let’s say I had a class Item and another class ItemHistory. ItemHistory has a property of type Item that refers to the Item class. Item, in turn, has an ICollection<ItemHistory> Histories property:
In my DbContext OnModelCreating() I have some code like this to set the foreign key names according to the company standard (capitalize ID, no underscores):
Likewise, I specified the primary keys like this:
In this way, I can use the C# convention of simply specifying the Id (in PascalCase) but still keep the database police happy with their standards. All of this is great except that as it stands now when the database is generated, the ItemHistory table has two foreign key columns:
Do you see what the problem is? I struggled for a bit trying to search for now to name the foreign key in entity framework code first, but of course everything says to either use MapKey() or if you are actually including the column IDs as properties on your entities, then you can use .HasForeignKey() as shown here. However, what I didn’t immediately realize because I wasn’t providing it any parameters anywhere else in my code is that .WithMany() takes an (optional) expression. So, if you want to specify the relationship on the other entity, you do it in .WithMany() like so:
Once that’s done, you should have only a single FK column generated in your database, and it should be the correct one (with ID not _Id1 suffix).