Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

\Unable to map entity to table if another entity has same name as table

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:

  • Widget
  • Gadget

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?

like image 619
Kevin Krueger Avatar asked Jul 20 '11 16:07

Kevin Krueger


2 Answers

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>();
like image 60
Alec Avatar answered Nov 09 '22 06:11

Alec


FYI: EF WorkItem 1641 noted above has been fixed on version 6.1.2

like image 39
Ben Ripley Avatar answered Nov 09 '22 04:11

Ben Ripley