42 lines
1.6 KiB
C#
42 lines
1.6 KiB
C#
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
|
using System.Text.Json.Serialization;
|
|
using System.Text.Json;
|
|
|
|
namespace Persistence.Database;
|
|
|
|
public static class EFExtensions
|
|
{
|
|
private static readonly JsonSerializerOptions jsonSerializerOptions = new()
|
|
{
|
|
AllowTrailingCommas = true,
|
|
WriteIndented = true,
|
|
NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals,
|
|
};
|
|
|
|
public static Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder<TProperty> HasJsonConversion<TProperty>(
|
|
this Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder<TProperty> builder)
|
|
=> HasJsonConversion(builder, jsonSerializerOptions);
|
|
|
|
public static Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder<TProperty> HasJsonConversion<TProperty>(
|
|
this Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder<TProperty> builder,
|
|
JsonSerializerOptions jsonSerializerOptions)
|
|
{
|
|
builder.HasConversion(
|
|
s => JsonSerializer.Serialize(s, jsonSerializerOptions),
|
|
s => JsonSerializer.Deserialize<TProperty>(s, jsonSerializerOptions)!);
|
|
|
|
ValueComparer<TProperty> valueComparer = new(
|
|
(a, b) =>
|
|
(a != null) && (b != null)
|
|
? a.GetHashCode() == b.GetHashCode()
|
|
: (a == null) && (b == null),
|
|
i => (i == null) ? -1 : i.GetHashCode(),
|
|
i => i);
|
|
|
|
builder.Metadata.SetValueComparer(valueComparer);
|
|
return builder;
|
|
}
|
|
|
|
}
|
|
|