Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework TPT Inheritance Subtypes

How can i determine the subtype of an entity with a TPT-Inhertiance?

If i have a base class Person and two subclasses Manager and Customer, it should be possible to query all persons and then group by their subclasses through using the GetType-Method, yet the returned type is always person. E.g.:

var persons = ctx.Persons.ToList();

var managers = persons.Where(x => x.GetType() == typeof(Manager)).ToList();
like image 767
narain Avatar asked Sep 03 '26 17:09

narain


1 Answers

Select:

var managers = ctx.Persons.OfType<Manager>().ToList();

also useful if you don't know what you have got

var persons = ctx.Persons.ToList();
Type modelType = persons.First().GetType();
if (modelType.BaseType == typeof(Manager))
{
    ((Manager)persons.First()).GiveNeilAPayRise = true;
}
like image 190
Neil Thompson Avatar answered Sep 05 '26 05:09

Neil Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!