< Summary

Information
Class: Elsa.Persistence.EFCore.JsonValueComparer<T>
Assembly: Elsa.Persistence.EFCore.Common
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Persistence.EFCore.Common/JsonValueComparer.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 13
Coverable lines: 13
Total lines: 49
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 6
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor()100%210%
Json(...)100%210%
DoGetSnapshot(...)0%620%
DoGetHashCode(...)0%620%
DoEquals(...)0%620%

File(s)

/home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Persistence.EFCore.Common/JsonValueComparer.cs

#LineLine coverage
 1using System.Text.Json;
 2using Microsoft.EntityFrameworkCore.ChangeTracking;
 3
 4namespace Elsa.Persistence.EFCore;
 5
 6/// <summary>
 7/// Compares two objects.
 8/// Required to make EF Core change tracking work for complex value converted objects.
 9/// </summary>
 10/// <remarks>
 11/// For objects that implement <see cref="ICloneable"/> and <see cref="IEquatable{T}"/>,
 12/// those implementations will be used for cloning and equality.
 13/// For plain objects, fall back to deep equality comparison using JSON serialization
 14/// (safe, but inefficient).
 15/// </remarks>
 016public class JsonValueComparer<T>() : ValueComparer<T>((t1, t2) => DoEquals(t1!, t2!),
 017    t => DoGetHashCode(t),
 018    t => DoGetSnapshot(t))
 19{
 20
 21    private static string Json(T instance) {
 022        return JsonSerializer.Serialize(instance);
 23    }
 24
 25    private static T DoGetSnapshot(T instance) {
 26
 027        if (instance is ICloneable cloneable)
 028            return (T)cloneable.Clone();
 29
 030        return JsonSerializer.Deserialize<T>(Json(instance))!;
 31    }
 32
 33    private static int DoGetHashCode(T instance) {
 34
 035        if (instance is IEquatable<T>)
 036            return instance.GetHashCode();
 37
 038        return Json(instance).GetHashCode();
 39
 40    }
 41
 42    private static bool DoEquals(T left, T right) {
 43
 044        if (left is IEquatable<T> equatable)
 045            return equatable.Equals(right);
 46
 047        return Json(left).Equals(Json(right));
 48    }
 49}