Entity framework Code First: select data from table with discriminator

.net ef-code-first entity-framework


First sorry if my title is not clear, but I do have hard time putting it as simple sentence in English :).

Let's say I have a website that manages, people and super heroes, I have 2 classes:

 public class Person
        public int PersonId { get; set; }

        public string Name { get; set; }    

  public class SuperHero:Person
        public string SuperHeroName { get; set; }
        public virtual ICollection<SuperPower> SuperPowers{ get; set; }

In my database I have this:

Person 1: Id = 1 Name ="Alex Flimster" Discrimiator= "Person"

Person 2 : ID = 2 Name="Bruce Wayne" discriminator="SuperHero" SuperHeroName="Batman"

I know if I do :

var test = from Context.Person select p;

I get everyone, hero or not.

If i want only hero I would do:

var test = from Context.Person.OfType<SuperHero>() select p;

My question is this: How do I get only the person?

var test = from Context.Person.OfType<Person>() select p; 

Will return the same as first test.

Edit I guess my question is not totally clear. Let's say I have 200 Person, and on top of that 10 superhero. I need a query that would return all Person that are just person and none of the possible heritant classes. (Let's say I have another class 'VideoGame Hero' that inherit from person as well. I would need a simple query that would be just person and none of the other classes)


4/2/2013 7:48:25 PM

Accepted Answer

Try this

from p in Context.Person
where !(p is SuperHero)
select p

Or fluent one

Context.Person.Where(p => !(p is SuperHero))

UPDATE: SQL will look like:

[Extent1].[Discriminator] AS [Discriminator], 
[Extent1].[PersonId] AS [PersonId], 
[Extent1].[Name] AS [Name], 
[Extent1].[SuperHeroName] AS [SuperHeroName]
FROM [dbo].[Person] AS [Extent1]
WHERE ([Extent1].[Discriminator] IN (N'SuperHero',N'Person')) 
      AND ([Extent1].[Discriminator] <> N'SuperHero')
4/2/2013 7:49:40 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow