Skip to content

Instantly share code, notes, and snippets.

@jiggak
Created November 30, 2023 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiggak/9f0d3a8fda5146b0b99171f6c49e6b2c to your computer and use it in GitHub Desktop.
Save jiggak/9f0d3a8fda5146b0b99171f6c49e6b2c to your computer and use it in GitHub Desktop.
C# JSON DB Column with update callback
namespace Foo.Bar;
public class FooBar : JsonColumn
{
public string? FooBar
{
get => GetValue<string?>("fooBar", null);
set => SetValue("fooBar", value);
}
}
using System.Text.Json;
namespace Foo.Bar;
public abstract class JsonColumn
{
protected Dictionary<string,object> obj = new Dictionary<string, object>();
protected Action<string>? onChange;
public static T Create<T>(string? json, Action<string> onChange)
where T : JsonColumn, new()
{
if (json != null)
{
var obj = JsonSerializer.Deserialize<Dictionary<string, object>>(json)!;
return new T()
{
obj = obj,
onChange = onChange
};
}
else
{
return new T()
{
onChange = onChange
};
}
}
protected T GetValue<T>(string name, T @default)
{
if (obj.ContainsKey(name))
{
return (T)obj[name];
}
return @default;
}
protected void SetValue<T>(string name, T val)
{
if (val != null)
{
obj[name] = val;
}
else if (obj.ContainsKey(name))
{
obj.Remove(name);
}
var json = JsonSerializer.Serialize(obj);
onChange?.Invoke(json);
}
}
namespace Foo.Bar;
[Table("MyTable")]
public class MyTable
{
[Column("fooBarJson")]
public string? FooBarJson { get; set; }
[NotMapped]
public FooBar FooBar => FooBar.Create<FooBar>(
FooBarJson,
json => FooBarJson = json
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment