summaryrefslogtreecommitdiff
path: root/src/marlin.web/Data/JsonValueComparer.cs
diff options
context:
space:
mode:
Diffstat (limited to 'src/marlin.web/Data/JsonValueComparer.cs')
-rw-r--r--src/marlin.web/Data/JsonValueComparer.cs23
1 files changed, 23 insertions, 0 deletions
diff --git a/src/marlin.web/Data/JsonValueComparer.cs b/src/marlin.web/Data/JsonValueComparer.cs
new file mode 100644
index 0000000..f07c133
--- /dev/null
+++ b/src/marlin.web/Data/JsonValueComparer.cs
@@ -0,0 +1,23 @@
+namespace marlin.web.Data;
+
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.ChangeTracking;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+public static class JsonValueComparer
+{
+ public static ValueComparer<T> Create<T>() => new(
+ (a, b) => JsonSerializer.Serialize(a, (JsonSerializerOptions?)null) == JsonSerializer.Serialize(b, (JsonSerializerOptions?)null),
+ v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null).GetHashCode(),
+ v => JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(v, (JsonSerializerOptions?)null), (JsonSerializerOptions?)null)!);
+}
+
+public static class PropertyBuilderExtensions
+{
+ public static PropertyBuilder<T> HasJsonConversion<T>(this PropertyBuilder<T> builder) =>
+ builder.HasConversion(
+ v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null),
+ v => JsonSerializer.Deserialize<T>(v, (JsonSerializerOptions?)null)!,
+ JsonValueComparer.Create<T>());
+}