I am developing an EF Code First for an existing database. Since they gave me the schema, and some of the table names are not perfect, I would name some entity classes differently than the base table and perform the mapping in OnModelCreating.
This does not work if the entity class name conflicts with the name of the existing table, even if I reassign them in code.
Given these (compiled for this example) entity classes:
I am trying to perform the following mappings in OnModelCreating:
modelBuilder.Entity<Gadget>.ToTable("Sprocket"); modelBuilder.Entity<Widget>.ToTable("Gadget");
At runtime, this results in the following error:
System.InvalidOperationException: Widget and Gadget object types cannot share the Gadget table because they are not in the hierarchy of the same type or have no real one-to-one relationship with a foreign key with the corresponding primary keys between them.
This does not make sense, as I am binding the Gadget object from the Gadget table, but it seems that some sort of mapping happens automatically, even if I specify it explicitly.
What is the explanation for this behavior and can it be circumvented?
source share