Search code examples
c#asp.net-coreinheritanceentity-framework-coreef-fluent-api

How can I list objects from abstract classes that include all specific subfields in EF Core?


I have been with this issue for some time now, and I have not seen a solution in either Microsoft's docs or on StackOverflow.

The issue: I have an abstract class, Workout:

public abstract class Workout
{
    public WorkoutType Type { get; set; }
    public List<Measurement> Measurements { get; set; } = new();

    // Id's and stuff
}

I have several subclasses that inherit from Workout, two examples:

RunningWorkout

public class RunningWorkout : Workout
{
    public double PersonalBest { get; set; }
}

and WeightWorkout

public class WeightWorkout : Workout
{
    public int PersonalBest { get; set; }
}

Now, I want to have an API endpoint where I get all the workouts of a user. However, I can only manage to get the fields that are in the base class. I have tried numerous ways to get all the subfields of the subclasses but to no avail. The "inheritance from derived types" does not work because the PersonalBest fields are not entities but primitive types.

Any ideas as to how I can get a list of all workouts that include all their own subproperties?


Solution

  • CodeCaster linked in a comment to 'How to serialize properties of derived classes with System.Text.Json', which said that you can add [JsonDerivedType(typeof(YourDerivedClassHere))] above your abstract class for all derived types.

    This serializes all subproperties of your derived classes, in my case when using aspnetcore at an API endpoint. This does not make it so you can access all derived subproperties in runtime, but as that was not my question, I will mark this as solved.