oldhowl

Untitled

Oct 6th, 2020
795
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  public static PropertyBuilder<T> HasJsonConversion<T>(this PropertyBuilder<T> propertyBuilder)
  2.             where T : class, new()
  3.         {
  4.             var converter = new ValueConverter<T, string>
  5.             (
  6.                 v => JsonConvert.SerializeObject(v,new JsonSerializerSettings()
  7.                 {
  8.                     NullValueHandling =  NullValueHandling.Ignore,
  9.                     ContractResolver = new CamelCasePropertyNamesContractResolver()
  10.                 }),
  11.                 v => JsonConvert.DeserializeObject<T>(v,new JsonSerializerSettings()
  12.                 {
  13.                     NullValueHandling =  NullValueHandling.Ignore,
  14.                     ContractResolver = new CamelCasePropertyNamesContractResolver()
  15.                 }) ?? new T()
  16.             );
  17.  
  18.             var comparer = new ValueComparer<T>
  19.             (
  20.                 (l, r) => JsonConvert.SerializeObject(l) == JsonConvert.SerializeObject(r),
  21.                 v => v == null ? 0 : JsonConvert.SerializeObject(v).GetHashCode(),
  22.                 v => JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(v))
  23.             );
  24.  
  25.             propertyBuilder.HasConversion(converter);
  26.             propertyBuilder.Metadata.SetValueConverter(converter);
  27.             propertyBuilder.Metadata.SetValueComparer(comparer);
  28.             propertyBuilder.HasColumnType("jsonb");
  29.  
  30.             return propertyBuilder;
  31.         }
  32.  
RAW Paste Data