Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you determine subtype of an entity using Inheritance with Entity Framework 4?

I am just starting to use the Entity Framework 4 for the first time ever. So far I am liking it but I am a bit confused on how to correctly do inheritance.

I am doing a model-first approach, and I have my Person entity with two subtype entities, Employee and Client. EF is correctly using the table per type approach, however I can't seem to figure out how to determine what type of a Person a specific object is.

For example, if I do something like

var people = from p in entities.Person select p;
return people.ToList<Person>();

In my list that I form from this, all I care about is the Id field so i don't want to actually query all the subtype tables (this is a webpage list with links, so all I need is the name and the Id, all in the Persons table).

However, I want to form different lists using this one query, one for each type of person (so one list for Clients and another for Employees).

The issue is if I have a Person entity, I can't see any way to determine if that entity is a Client or an Employee without querying the Client or Employee tables directly. How can I easily determine the subtype of an entity without performing a bunch of additional database queries?

like image 384
KallDrexx Avatar asked Sep 21 '25 02:09

KallDrexx


1 Answers

Use .OfType<Client>() in your query to get just the clients. See OfType.

e.g. entities.Person.OfType<Client>() ...

Use is to test if a Person object is a specific sub-class, e.g. if (p is Employee) ...

BTW why isn't it entities.People? Did you not select the pluralization option?

like image 98
Ian Mercer Avatar answered Sep 23 '25 12:09

Ian Mercer