I have a postgres table with a jsonb column. This jsonb column has an object with an enum in it. The db stores the enum as text.
However EF seems to use system.text.json to serialize/deserialize into the DB. I would like to use Newtonsoft.Json instead. But cannot find a way to achieve this
The reason i want to change is because system.text.json is less flexible.
As you can see in the code below, system.text.json fails with a
System.Text.Json.JsonException: The JSON value could not be converted to MyEnum. Path: $.Trigger | LineNumber: 0 | BytePositionInLine: 21.
whilst newtonsoft.json works fine.
Can be replicated as below
public class Program
{
public enum MyEnum { Hello=0, World }
public class MyModel
{
public MyEnum Trigger { get; set; }
public string Name { get; set; }
}
public static void Main()
{
var a = @"{ ""Trigger"": ""Hello"", ""Name"": ""Stack""}";//does not with system.text.json
var b = @"{ ""Trigger"": 1, ""Name"": ""Stack""}";//works
var newtonA = Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel>(a);
var newtonB = Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel>(b);
//var systemA = JsonSerializer.Deserialize<MyModel>(a); //uncomment for failure
var systemB = JsonSerializer.Deserialize<MyModel>(b);
Console.WriteLine(newtonA.Trigger);
Console.WriteLine(newtonB.Trigger);
//Console.WriteLine(systemA.Trigger); //uncomment for failure
Console.WriteLine(systemB.Trigger);
}
}
In my code i select from the DB as below.
public async Task<MyModel> GetMyModel(string id)
{
IQueryable<MyModel> query = dbSet;
query = query
.Where(w => w.Id == id)
var res = await query.SingleAsync();
return res;
}
dbSet is a DbSet<TEntity>