Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework : Filter query by property of a child type

I have model as below

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Employee : Person
{
    public string Dep { get; set; }
}

class Client : Person
{
    public string Type { get; set; }
}

Now I would like to query Person by a property of Employee as follows

context.Set<Person>().Where(x => ((Employee)x).Dep == "dep").ToList();

But I get the following error

Unable to cast the type 'DomainModel.Person' to type 'DomainModel.Employee'. LINQ to Entities only supports casting EDM primitive or enumeration types.

I know that I could simply use

context.Set<Employee>().Where(x => x.Dep == "dep").ToList();

But the problem is that I use a generic search control, that control can deal only with one type to search into, the search criteria are passed to this control as lambda expressions of that determined type and search statements are also returned by the search control as lambda expressions that then are passed as predicate to the Where method, now I would like to use this search control to search Employee and Person at the same time, and since the search control can deal with only one type I passed the parent type to it which is Person so that I can access all its children types properties in the search, but I faced the problem mentioned above. Any idea?

like image 334
Sisyphus Avatar asked Oct 30 '17 11:10

Sisyphus


1 Answers

When it comes to EF inheritance, the cast operator is not supported in LINQ to Entities query. However, the is and as operator are perfectly supported, so the correct way of writing such filters is like this:

context.Set<Person>()
    .Where(x => x is Employee && (x as Employee).Dep == "dep")
    .ToList();
like image 168
Ivan Stoev Avatar answered Nov 14 '22 21:11

Ivan Stoev