We've got a code first approach in our application. We have a simple hierarchy similar to this:
SuperSpecializedPerson extends SpecializedPerson extends (abstract) Person
We've got two repositories for SuperSpecializedPerson and SpecializedPerson. When querying for SuperSpecializedPerson, the returned entities are the wanted ones. When querying for SpecializedPerson, all SpecializedPerson as well as SuperSpecializedPerson (as an instances of SpecializedPerson) are being returned. This is my issue.
Checking the SQL query is see this part of code WHERE ([Extent1].[Discriminator] IN (N''SuperSpecializedPerson '',N''SpecializedPerson''))
, where I'd like to have WHERE ([Extent1].[Discriminator] IN (N''SpecializedPerson''))
.
How can I get only SpecializedPerson?
[edit] I'll give some more context to my issue to figure out if I am on the wrong track altogether:
I have to return a list of DTOs of the same type from the backend to the frontend. The DTOs are being created with Automapper according to the specified mapping profiles.
First I query for SuperSpecializedPerson, map them to DTO, then the same happens for SpecializedPerson and concatenate both lists. After merging, I get two instances of all SuperSpecializedPerson (once with only the SpecializedPerson properties).
The described model has been defined according to the current knowledge and will probably in future to have a second class extending SpecializedPerson.
This happens because SuperSpecializedPerson
is also a SpecializedPerson
. This a fundamental aspect of inheritance. A cat is an animal. The keyword is
includes derived types.
Query with
context.SpecializedPersons.Where(p => !(p is SuperSpecializedPerson));
Another approach not as performing as this one but also working with additional derived types in future, is to filter with LINQ-to-Objects
context.SpecializedPersons
.Where(p => /* other filters go here */)
.AsEnumerable() // Switches to LINQ to Objects
.Where(p => p.GetType() == typeof(SpecializedPerson));
Your edit says that the problem is the mapping with automapper. See automapper documentation for Mapping Inheritance. Especially the part with Runtime polymorphism.