From 9fb7f980def22592e9adc82bdf354ba99ccec067 Mon Sep 17 00:00:00 2001 From: rgb4321 <123187819+rgb4321@users.noreply.github.com> Date: Thu, 16 Feb 2023 09:13:53 -0600 Subject: [PATCH] Update DataSetConverter.cs Typed datasets are serialized in whatever order tables were added (usually via the designer). If there is a foreign key constraint and the child table happened to be added by the developer prior to the parent table, deserialization could fail with an InvalidConstraintException. To avoid that, set EnforceConstraints to false prior to deserializing the dataset and then set it back to true when deserialization is complete. --- Src/Newtonsoft.Json/Converters/DataSetConverter.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs index 214728e67..a6843880e 100644 --- a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs @@ -85,7 +85,8 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer DataSet ds = (objectType == typeof(DataSet)) ? new DataSet() : (DataSet)Activator.CreateInstance(objectType)!; - + ds.EnforceConstraints = false; // necessary in case the typed dataset contains foreign key constraints and the tables were serialized out of order + DataTableConverter converter = new DataTableConverter(); reader.ReadAndAssert(); @@ -105,6 +106,9 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer reader.ReadAndAssert(); } + // once all tables are populated there should be no foreign key constraint violations so reset EnforceConstraints + ds.EnforceConstraints = true; + return ds; } @@ -122,4 +126,4 @@ public override bool CanConvert(Type valueType) } } -#endif \ No newline at end of file +#endif