\ It is not possible to match an entity with a table if another object has the same name as the table

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:

  • Widget
  • Gadget

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?

+6
source share
3 answers

Are your entities and table names singular?

I ask that if you try to do something like

 modelBuilder.Entity<Gadget>.ToTable("Sprockets") modelBuilder.Entity<Widget>.ToTable("Gadgets") 

it may not work because EF: CF matches objects to their multiple tables by convention. If you want to delete this agreement, simply delete PluralizingTableNameConvention .

 modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
+2
source

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

+1
source

It looks like this when the table has the same name in a different schema . To date, there is no support for EF in this aspect. For instance:.

 dict.Gadget cnfg.Gadget 

Please check https://entityframework.codeplex.com/workitem/1641 and vote to increase the importance of this fix.

0
source

Source: https://habr.com/ru/post/893185/


All Articles