question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Reverse engineer error: The foreign key {'AssessmentId'} cannot be added to the entity type 'AssessOst' because a foreign key on the same properties already exists on entity type 'AssessOst' and also targets the key {'AssessmentId'} on 'Assessment'

See original GitHub issue

While attempting to scaffold a database, I encountered this error:

System.Exception: Reverse engineer error: 
System.InvalidOperationException: The foreign key {'AssessmentId'} cannot be added to the entity type 'AssessOst' because a foreign key on the same properties already exists on entity type 'AssessOst' and also targets the key {'AssessmentId'} on 'Assessment'.
   at Microsoft.EntityFrameworkCore.Metadata.Internal.ForeignKey.Validate(IReadOnlyList`1 properties, Key principalKey, EntityType declaringEntityType, EntityType principalEntityType)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.ForeignKey..ctor(IReadOnlyList`1 dependentProperties, Key principalKey, EntityType dependentEntityType, EntityType principalEntityType, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityType.AddForeignKey(IReadOnlyList`1 properties, Key principalKey, EntityType principalEntityType, Nullable`1 componentConfigurationSource, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityType.Microsoft.EntityFrameworkCore.Metadata.IMutableEntityType.AddForeignKey(IReadOnlyList`1 properties, IMutableKey principalKey, IMutableEntityType principalEntityType)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitForeignKey(ModelBuilder modelBuilder, DatabaseForeignKey foreignKey)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitForeignKeys(ModelBuilder modelBuilder, IList`1 foreignKeys)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitDatabaseModel(ModelBuilder modelBuilder, DatabaseModel databaseModel)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.Create(DatabaseModel databaseModel, ModelReverseEngineerOptions options)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions databaseOptions, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
   at ReverseEngineer20.ReverseEngineer.ReverseEngineerRunner.GenerateFiles(ReverseEngineerCommandOptions reverseEngineerOptions) in C:\Code\EFCorePowerTools\src\GUI\RevEng.Core\ReverseEngineerRunner.cs:line 114
   at efreveng.Program.Main(String[] args) in C:\Code\EFCorePowerTools\src\GUI\efreveng\Program.cs:line 68

   at EFCorePowerTools.Handlers.ReverseEngineer.ResultDeserializer.BuildResult(String output) in C:\projects\efcorepowertools\src\GUI\EFCorePowerTools\Handlers\ReverseEngineer\ResultDeserializer.cs:line 27
   at ReverseEngineer20.ReverseEngineer.EfRevEngLauncher.GetOutput() in C:\projects\efcorepowertools\src\GUI\EFCorePowerTools\Handlers\ReverseEngineer\EfRevEngLauncher.cs:line 112
   at ReverseEngineer20.ReverseEngineer.EfRevEngLauncher.LaunchExternalRunner(ReverseEngineerOptions options, Boolean useEFCore5) in C:\projects\efcorepowertools\src\GUI\EFCorePowerTools\Handlers\ReverseEngineer\EfRevEngLauncher.cs:line 51
   at EFCorePowerTools.Handlers.ReverseEngineerHandler.<ReverseEngineerCodeFirstAsync>d__3.MoveNext() in C:\projects\efcorepowertools\src\GUI\EFCorePowerTools\Handlers\ReverseEngineerHandler.cs:line 272

After speaking with my database guy, he said the likely issue is that the vendor for this db uses a combined PK and FK to enforce a 1:0/1:1 relationship between two tables, and that this is apparently an uncommon (as far as he is aware) scenario. So my first guess is that the scaffolder is getting hung up on this.

A few Google searches seem to suggest that having keys like this can be defined via code-first, but I don’t know if being able to reverse-engineer this is more of an EF team issue than a Power Tools issue specifically.

Steps to reproduce

I was able to create a new test database with only the two tables related to this issue, strip out all the other columns for simplicity, and reproduce the issue. The following SQL should create the tables and reproduce the issue when scaffolded:

/* Create the Assessment table first */

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Assessment](
	[AssessmentID] [int] IDENTITY(1,1) NOT NULL,
	[CreatedDate] [date] NOT NULL,
 CONSTRAINT [PK_Assessment] PRIMARY KEY CLUSTERED 
(
	[AssessmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Assessment] ADD  CONSTRAINT [DF_Assessment_CreatedDate]  DEFAULT (GETDATE()) FOR [CreatedDate]
GO

/* Now create the AssessOST table, which depends on Assessment */

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[AssessOST](
	[AssessmentID] [INT] NOT NULL,
	[CreatedDate] [DATE] NULL,
 CONSTRAINT [PK_AssessOST] PRIMARY KEY NONCLUSTERED 
(
	[AssessmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[AssessOST] ADD  DEFAULT (GETDATE()) FOR [CreatedDate]
GO

ALTER TABLE [dbo].[AssessOST]  WITH NOCHECK ADD  CONSTRAINT [CONAssessOSTAssessmentIDAssessmentAssessmentID] FOREIGN KEY([AssessmentID])
REFERENCES [dbo].[Assessment] ([AssessmentID])
GO

ALTER TABLE [dbo].[AssessOST] CHECK CONSTRAINT [CONAssessOSTAssessmentIDAssessmentAssessmentID]
GO

ALTER TABLE [dbo].[AssessOST]  WITH NOCHECK ADD  CONSTRAINT [FK_AssessOST_Assessment] FOREIGN KEY([AssessmentID])
REFERENCES [dbo].[Assessment] ([AssessmentID])
GO

ALTER TABLE [dbo].[AssessOST] CHECK CONSTRAINT [FK_AssessOST_Assessment]
GO

As I’m not an SQL guy, I apologize if a lot of that could have been omitted!

After using that script in an empty SQL Server database, attemptying to then scaffold it causes the error above.

Further technical details

EF Core Power Tools version: 2.5.306.0

Database engine: Microsoft SQL Server 2016 (SP2-CU9) (KB4515435) - 13.0.5479.0 (X64)

Visual Studio version: Visual Studio 2019 16.8.1

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
smitpatelcommented, Nov 19, 2020

Filed issue on EF Core.

0reactions
ErikEJcommented, Nov 26, 2020

Will be fixed in EF Core 6

Read more comments on GitHub >

github_iconTop Results From Across the Web

Foreign key on the same properties already exists
The foreign key {'ForeignKeyId'} cannot be added to the entity type 'TABLENAME' because a foreign key on the same properties already exists ......
Read more >
ODI Reverse Engineer Does Not Correctly Import Foreign ...
The foreign key is shown under the Model in the Datastore. Click 'Expand Constraints' to see the keys there. * It has another...
Read more >
Reverse engineer and discover foreign keys - HeliFromFinland
There are two ways Data Modeler can guess the foreign keys for you: the column has the same name as a primary key...
Read more >
Untitled
InvalidOperationException: The foreign key {'AssessmentId'} cannot be added to the entity type 'AssessOst' because a foreign key on the same properties already ......
Read more >
ER Studio Data Architect
Object Types tab . ... Reverse Engineering an Existing Database . ... Create a new diagram with one entity called Entity1 with a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found