So, I found out that EF Core works just fine, it was the Controller which lost the polymorphic properties of the children during the API call.
To get the derived classes I simply used:
var household = Context.Households.Where(h => h.Id = id)
.Include(hp => hp.Persons).FirstOrDefault();
To solve the issue with the controller I used the following two sources as a guideline, DotNet Serialization and Polymorphic Deserialization.
I based by implementation of a JsonConverter on it, and ended up with the following code:
Edited class:
public class Household {
public int Id {get; set;}
public virtual ICollection<Person> Persons {get; set;}
}
public abstract class Person {
public int Id {get; set;}
public string Discriminator {get; private set;}
// The discriminator actually exists in the inherited parent table,
// I just want to attach it to my entities so I can identify to which subclass it belongs to
}
public class Parent : Person {
public int Income {get; set;}
}
public class Child : Person {
public string School {get; set;}
}
JsonConverter:
public class PersonConverter: JsonConverter<Person>
{
public override bool CanConvert(Type typeToConvert) =>
typeof(Person).IsAssignableFrom(typeToConvert);
public override Person Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException();
}
Person person;
using (var jsonDocument = JsonDocument.ParseValue(ref reader))
{
// Using camelCase properties in my front-end application, therefore ToLower()
if (!jsonDocument.RootElement.TryGetProperty(nameof(Person.Discriminator).ToLower(), out var typeProperty))
{
throw new JsonException();
}
var type = typeProperty.GetString();
var jsonObject = jsonDocument.RootElement.GetRawText();
switch (type)
{
case nameof(Parent):
person = (Parent)JsonSerializer.Deserialize(jsonObject, typeof(Parent));
break;
case nameof(Child):
person = (Child)JsonSerializer.Deserialize(jsonObject, typeof(Child));
break;
default:
throw new JsonException();
}
}
return person;
}
public override void Write(Utf8JsonWriter writer, Person value, JsonSerializerOptions options)
{
if (value is Parent parent)
{
// Using camelCase properties in my front-end application
JsonSerializer.Serialize(writer, parent, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
}
else if (value is Child child)
{
// Using camelCase properties in my front-end application
JsonSerializer.Serialize(writer, child, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
}
else
{
throw new NotSupportedException();
}
}
}
I then attached it to my controller during startup.
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new PersonConverter());
});