1

I am having trouble casting a collection of child entities of a base class to all derived classes. Let me provide you with an example:

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 class Parent : Person {
    public int Income {get; set;}
}

public class Child : Person {
    public string School {get; set;}
}

The issue arises when I try to select an entity of the Household class with the child collection Persons when I want to cast the children to their specific derived classes.

I've tried the following queries without success:

var household = Context.Households.Where(h => h.Id = id)
                .Include(hp => hp.Persons).OfType<Parent>().OfType<Child>()
                .FirstOrDefault();

(generates error that Class Child does not contain the correct definitions).

var household = Context.Households.Where(h => h.Id = id)
                .Include(hp => hp.Persons).OfType<Parent>()
                .Include(hpp => hpp.Persons).OfType<Child>()
                .FirstOrDefault();

(generates the error that the class Parent does not contain a definition for Person)

What I would like is to have a collection of both derived classes on the Household entity, and not just the base class.

Pannkakan
  • 91
  • 6

1 Answers1

0

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());
});
Pannkakan
  • 91
  • 6