Getting entities of a certain type using entity frameworks return error - LINQ to Entities does not recognize the method 'System.Type GetType()'

Refresh

February 2019

Views

1k time

1

I am trying to filter out entities of a certain type. I am using Entity Framework, and I have a parent entity, and various children that inherit from the parent entity. I am trying to filter out one of these children.

For example, I have the following structure:

  • Address : Entity
    • PostCode : Address
    • Street : Address

A User entity has a reference to one address. How can I obtain a list of users that are associated to an address of type PostCode?

i.e. I tried:

 var query = from User p in context.Users
                        where p.Address.GetType() == typeof(PostCode)
                        select p;

But I get:

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

I have seen couple of solutions that involve obtaining the list of Users first, and then selecting those of a certain type. Problem with this solution is that the query obtains all the users first; I would like my query to include the filter since I have quite a few Users.

Thanks!

1 answers

4

Try using is operator.

 var query = from User p in context.Users
                    where p.Address is PostCode
                    select p;