I am currently working on a database table, that shall contain some base properties of the data and one property that is a jsonb column in the database that can contain different objects that are derived from one base class.
I am using Entity Framework Core 9.0.2 and Npgsql 9.0.3.
Here is an example for the entity:
public class DatabaseEntity
{
public int Id { get; set; }
// This is the jsonb column
public BaseClass DerivedClassProperty { get; set; }
}
And this is an example for the class hierarchy that shall be stored in the jsonb column of the entity:
[JsonPolymorphic]
[JsonDerivedType(typeof(A))]
[JsonDerivedType(typeof(B))]
public class BaseClass
{
public int BaseProperty { get; set; }
}
public class A : BaseClass
{
public int AdditionalProperty { get; set; }
}
public class B : BaseClass
{
public string AnotherProperty { get; set; }
}
In EF I added the entity by defining it this way:
modelBuilder.Entity<DatabaseEntity>().ToTable("DatabaseEntity")
.OwnsOne(b => b.Properties, onb => onb.ToJson());
The migrations (we are using code first) have been generated, the database table is exactly what I expect, however, if I try to save the entity with e.g. class "A" in DerivedClassProperty, it only persists the properties of the BaseClass and not the ones of the derived class.
As far as I understand, this is the correct way on how to handle POCOs for jsonb tables in the latest version of Npsql and EF Core 9 (Npsql documentation).
I already tried to use the legacy way, which is described in the link to the Npgsql documentation above, but this also did not work.
Has anybody experienced something like this and knows how to set it up, so that the derived classes get persisted correctly?