Attempting to perform a hierarchical update results in the error "Foreign key value cannot be inserted"

I am a bit noob with DAO and SQL Server, and I am having a problem when I try to insert values ​​into two tables that are related. A table Photoshas a field gpsIdthat has a foreign key relationship with a idtable field GPSLocations. I want to create a new Photos entry associated with the new GPSLocation, so the code looks something like this:

gpsRow = dataset.GPSLocations.AddGPSLocationsRow("0.0N", "3.2W");
dataset.Photos.AddPhotosRow(@"c:\path\file.jpg", gpsRow);
tableAdapterManager.UpdateAll(dataset); 

However, this results in the following error:

A foreign key value cannot be inserted because the corresponding primary key of the value does not exist. [Foreign key constraint name = photoToGps]

I am using SQL Server CE. As far as I understand, what TableAdapterManagershould this hierarchical update handle? I simply dragged these tables into the XSD view and relied on its automatic creation of wrapper classes. Do I need to change anything regarding a relationship (for example, to restrict a foreign key)? I noticed that in some cases the gps id is positive and sometimes negative, which is relevant?

EDIT: I also guaranteed that the update property is set to CASCADE, which leads to the same error. Hierarchical updates are set to true, and there is a foreign key constraint between the two tables in the designer.

+3
5

, SQL Server CE SQL Server. , , - , , . DataSet , ​​ , . , , , TableAdapterManager INSERT, SELECT, . SQL Server CE , , , SELECT, RowUpdated. MSDN .

+2
+3

, ?

+1

( , XSD)? -, .

+1
source

Since the photoToGps (foreign key) column is dependent on the primary key (id), you cannot add photoToGps if there is no corresponding identifier. So what you need is separate updates, not UpdateAll. First update the GPSLocations table, and then another table. This way you will have an existing identifier before you add photoToGPS for it.

0
source

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


All Articles