Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key conflict ef core scaffolding

The foreign key {'ClassExtId'} cannot be added to the entity type 'ClassInt' because a foreign key on the same properties already exists on entity type 'Instrument' and also targets the key {'ClassExtId'} on 'ClassExt'.

Let's say I have ClassFoo & ClassBar inheriting from ClassInt. Each one of them have a reference to the same column ClassExtId. Why is the entity framework core scaffolding (v3) complaining ?

like image 471
sofsntp Avatar asked Oct 15 '19 09:10

sofsntp


People also ask

Does EF core have foreign key?

The Entity Framework Core Fluent API HasForeignKey method is used to specify which property is the foreign key in a relationship. In the following example, the AuthorFK property in the Book entity does not follow Entity Framework Core's convention for foreign key names.

Is Scaffold-DbContext command is used in EF Code First approach?

Entity Framework Core supports Database-First approach via the Scaffold-DbContext command of Package Manager Console. This command scaffolds a DbContext and entity type classes for a specified database.

Will Cascade delete Entity Framework Core?

The EF Core in-memory database does not currently support cascade deletes in the database.


1 Answers

my case is different but i got the same error too when i was trying to scaffold my existing old database. i'm, posting this answer just in case someone also had the same problem with me.

it's turn out that in my old database, some table have so many duplicate foreign key created by previous developer. you can check this in your sql server (i use sql server developer edition 2019)

  1. In Object Explorer, right-click the table that will be on the foreign-key side of the relationship and click Design.
    The table opens in Table Designer.

  2. From the Table Designer menu, click Relationships. you'll see all the foreign key defined for that table, in my case it was applicationID that duplicate. clean it up : enter image description here

  3. go to your table > expand it and go to Keys. delete the duplicate key there: enter image description here

  4. run your dotnet ef dbcontext scaffold command and good luck!
like image 160
winwizardy Avatar answered Sep 18 '22 17:09

winwizardy