Search code examples
c#.netentity-frameworkoftype

Filtering derived classes in Entity set by OfType and getting exception


I am trying to filter derived classes in my entities but i am getting exception.

var filtered = db.PersonSet.OfType<Person>().
               Where(person =>person.GetType()==typeof(Person))

I am getting below exception if i try to loop filtered collection by foreach.

"LINQ to Entities does not recognize the method 'System.Type GetType()' method, and this method cannot be translated into a store expression.".

How can i overcome it ? What can be alternative way for filtering ?


Solution

  • Try this:

    var persons= db.PersonSet.OfType<Person>().ToList();
    var filtered = persons.Where(person =>person.GetType()==typeof(Person))
    

    This should work, but it's unnecessary. The first line should ensure that you only get objects of type Person.