Switch to JSON.NET
See original GitHub issueHello,
This feels more like a question that an actual issue. But didn’t know for sure where to ask otherwise
These are early days for EF Core JSON support, and you’ll likely run into some limitations. Please let us know how the current features are working for you and what you’d like to see.
So I’m playing a bit with the JSON support and I really like it. There is one problem I’m having since internally the ‘new’ System.Text.Json api is used there is no support for polymorphic serialization and deserialization (https://github.com/dotnet/runtime/issues/30083)
I could easily solve this in the following way:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<RootEntity>()
.Property(e => e.ChildrenA)
.HasConversion(
v => JsonConvert.SerializeObject(v, JsonSettings.JsonSerializerSettings),
v => JsonConvert.DeserializeObject<ImmutableList<AbstractClassA>>(v, JsonSettings.JsonSerializerSettings));
modelBuilder.Entity<RootEntity>()
.Property(e => e.ChildrenB)
.HasConversion(
v => JsonConvert.SerializeObject(v, JsonSettings.JsonSerializerSettings),
v => JsonConvert.DeserializeObject<ImmutableList<AbstractClassB>>(v, JsonSettings.JsonSerializerSettings));
}
}
public static class JsonSettings
{
public static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
};
}
This perfectly works. But it’s a bit tedious to always add this in the model creation. Is there a better solution like globally replacing System.Text.Json to good 'ol JSON.NET?
Btw I’m using the preview of EF Core 6.
Thanks in advance, Sincerely, Brecht
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)
There should be converter samples in those issues (though deserialization is a different matter) that you could copy paste into your app but I think that all hinges on https://github.com/npgsql/efcore.pg/issues/1107?
One main reason why JSON.NET wasn’t implemented, was that we don’t want to add a reference to JSON.NET from EFCore.PG itself - that would force it upon users and potentially created dependency hell situations (System.Text.Json has the advantage of being built into the framework). EF Core does have a plugin model which allows having external nugets which add the reference, but the JSON support requires certain advanced functionality which isn’t possible from a plugin.
Then there’s the burden of maintaining two JSON implementations rather than just one… System.Text.Json has generally been improving and closing the gap, so this doesn’t really seem like a good way forward.