Created
November 30, 2023 18:26
-
-
Save jiggak/9f0d3a8fda5146b0b99171f6c49e6b2c to your computer and use it in GitHub Desktop.
C# JSON DB Column with update callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Foo.Bar; | |
public class FooBar : JsonColumn | |
{ | |
public string? FooBar | |
{ | |
get => GetValue<string?>("fooBar", null); | |
set => SetValue("fooBar", value); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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