I am doing EF Code First development against an existing database. Since I was handed a schema and some of the table names aren't ideal, I'd like to name certain entity classes differently than the underlying table and perform the mapping in OnModelCreating.
This doesn't seem to work if a entity class name conflicts with an existing table name, even if I remap them in code.
Given these (made up for this example) entity classes:
I'm attempting to perform the following mappings in OnModelCreating:
modelBuilder.Entity<Gadget>.ToTable("Sprocket");
modelBuilder.Entity<Widget>.ToTable("Gadget");
At runtime, this yields the following error:
System.InvalidOperationException : The entity types 'Widget' and 'Gadget' cannot share table 'Gadget' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
This doesn't make sense as I'm mapping the Gadget entity away from the Gadget table but it appears some mapping is happening automatically even though I'm specifying it explicitly.
What is the explanation for this behavior, and can it be worked around?
Are your entities and table names singular?
The reason I ask is that if you were trying to do something like
modelBuilder.Entity<Gadget>.ToTable("Sprockets")
modelBuilder.Entity<Widget>.ToTable("Gadgets")
it might not work because EF:CF maps entities to their pluralized tables by convention. If you would like to remove this convention, simply remove the PluralizingTableNameConvention.
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
FYI: EF WorkItem 1641 noted above has been fixed on version 6.1.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With