views:

31

answers:

2

Hello everybody

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 ?

+1  A: 

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.

Dave Swersky
@Dave Swersky It is working as i wanted but why this exception occur ?
Freshblood
@Freshblood the exception is happening because it was trying to put the cast into the SQL statment. You have to first get the object back, then filter them.
Jerod Houghtelling
A: 

The minute you do the toList, the query is executed and filtering is too late. If you setup an object query then add a Group by clause after your where clause it should perform the secondary filter you want. It is my understanding that the group by clause is for secondary filtering of the results set.