This is doing my head in. I have a pretty simple model class like this (generated by EF Core Power Tools):
In the Azure SQL database, I have the following foreign key relationship in place which associates a Sighting record with to every MachineLearningTaggedImage record:
ALTER TABLE [dbo].[MachineLearningTaggedImage] WITH CHECK
ADD CONSTRAINT [FK_MachineLearningTaggedImage_Sighting]
FOREIGN KEY([SightingId]) REFERENCES [dbo].[Sighting] ([SightingId])
GO
ALTER TABLE [dbo].[MachineLearningTaggedImage]
CHECK CONSTRAINT [FK_MachineLearningTaggedImage_Sighting]
GO
I am then trying to do a very run of the mill insert, with the SightingId value populated (because I want the newly inserted MachineLearningTaggedImage record to link to an existing Sighting record that already exists in the database):
var newImageTag = new MachineLearningTaggedImage
{
SightingId = sighting.SightingId
};
_db.MachineLearningTaggedImages.Add(newImageTag);
Save();
But the insert fails with the following error:
The MERGE statement conflicted with the FOREIGN KEY constraint "FK_MachineLearningTaggedImage_Sighting". The conflict occurred in database "MyDatabase", table "dbo.Sighting", column 'SightingId'.
I'm puzzled because my existing value of SightingId (3398670) definitely exists in the Sighting table as an existing record which I want to link to.
But for some reason, EF Core or SQL won't let me do this insert.
Now if I go directly into a SQL query window (outside of EF Core), I can successfully insert the new MachineLearningTaggedImage record with a SightingId value = 3398670 - no problem at all. It works..
What am I running into? Is it something related to me having only populated the SightingId value, but the actual Sighting child / related object property is still null when I attempt to insert? I thought you could simply populated an ID of a related object and EF Core would be happy with that.
