Entity Framework : Filter query by property of a child type

匆匆过客 提交于 2021-02-05 05:10:21

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/47013668/entity-framework-filter-query-by-property-of-a-child-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!