Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework Code First: select data from table with discriminator

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
    {      
        [Key]
        public int PersonId { get; set; }

        [MaxLength(100)]
        public string Name { get; set; }    
    }

  public class SuperHero:Person
    {    
        [MaxLength(100)]
        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)

Thanks!

like image 202
Tom Avatar asked Apr 02 '13 19:04

Tom


1 Answers

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:

SELECT 
[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')
like image 186
Sergey Berezovskiy Avatar answered Sep 28 '22 18:09

Sergey Berezovskiy