I had the same problem and I found two things:
- The conventions used to match column names are names such as User_UserID and User_ID, not UserID. Solutions:
- You can change the conventions used. I do not understand if this is possible in EF 4.1. Scott Gu has a post complaining that this is not the case, but I see the Conventions property hanging over the ModelBuilder class ... with only one method ... Add ().
- You can specify the name of the foreign key explicitly (see below).
- I had cases where I really fixed it in StackOverflow suggestions, but the cached DbModel meant that it was still broken until I actually shut down Cassini and caused the dev web server to completely reboot.
Unfortunately, since you are not using naming conventions that imply frameworks, you will have to continue to use the ForeignKey attribute in all of your classes so that everything binds correctly, or it displays the wrong column name.
Setting up the foreign key name looks like this:
[ForeignKey("UserID")] public virtual User User { get; set; }
This explicitly tells the platform to use UserID instead of User_UserID
In many-to-many cases, you need to use the above Map call and apply the ForeignKey attribute on both sides.
This resolved it for me.
Now I see why Scott complained about leaving the Conventions - it really burned out when you try to collect things in an existing database.
source share