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 issueWhile 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:
- Created 3 years ago
- Comments:7 (5 by maintainers)
Top GitHub Comments
Filed issue on EF Core.
Will be fixed in EF Core 6