Reputation: 4123
I was using CTP5 and switched to RC1. With no changes to the EntityTypeConfiguration, EF is now trying to look something up by the wrong column name. It is using the singular rather than the plural of the column name and I can't figure out where it is getting that idea.
Example: Many-to-many
//User.Roles
//Role.Users
//User EntityTypeConfiguration
this.HasKey(x => x.Id);
this.HasMany(x => x.Roles)
.WithMany().Map(m => {
m.MapLeftKey("Users_Id");
m.MapRightKey("Roles_Id");
m.ToTable("UserRoleLinks");
});
Then I get the error:
Invalid column name 'User_Id'.
Where is it getting "User_Id"? The table Id is "Id"; The join table is explicitly stated as "Users_Id" What changed between CTP5 and RC1 that would have caused this?
UPDATE:
I am using the "modelBuilder.Conventions.Remove<IncludeMetadataConvention>()" is that one not supported anymore? Could this be the problem? I'm not sure what the default behavior is now.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Configurations.Add(new UserConfig());
}
Upvotes: 3
Views: 3476
Reputation: 4123
I figured out what I was doing wrong. The short answer is that I needed to define both sides of the many-to-many relationship because each class participates with a reciprocal collection (User.Roles and Role.Users). Apparently that wasn't necessary with CTP5.
See: Many to Many mapping not working - EF 4.1 RC
To stick with my example, here is the correct syntax.
this.HasMany(x => x.Roles)
.WithMany(r => r.Users).Map(m => {
m.MapLeftKey("Users_Id");
m.MapRightKey("Roles_Id");
m.ToTable("UserRoleLinks");
});
There are a couple pitfalls which obscured the simple solution for me.
1) Only define the relationship once. I was defining the many-to-many relationship from both perspectives in different EntityTypeConfiguration<T> classes, which is not necessary and brings its own errors.
2) Don't mix up the fields you use for the MapLeftKey and MapRightKey. The order is intuitive but I am guessing it is easily something that could get mixed up through copy/paste and what-not.
Upvotes: 4
Reputation: 16204
The Foreign Key naming convention changed in EF 4.1 RC
.
The problem is basically that EF now expects the FK to be called User_ID
(singular), and the RC provides no ability to configure custom conventions.
If EF recreated the database for you, just change your mappings to User_Id
. If you're stuck with a production database I'd recommend using sp_rename to rename the Foreign Keys in your database.
This answer (gotten from a question of mine, see below) worked for me painlessly and seamlessly on a production database.
Upvotes: 0