简体   繁体   English

实体框架:按子类型的属性筛选查询

[英]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 现在我想通过Employee的属性查询Person ,如下所示

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'. 无法将类型“DomainModel.Person”强制转换为“DomainModel.Employee”。 LINQ to Entities only supports casting EDM primitive or enumeration types. LINQ to Entities仅支持转换EDM原语或枚举类型。

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. 但问题是我使用通用搜索控件,该控件只能处理一种类型进行搜索,搜索条件作为该确定类型的lambda表达式传递给该控件,搜索控件也将搜索语句返回然后将lambda表达式作为谓词传递给Where方法,现在我想使用此搜索控件同时搜索EmployeePerson ,并且由于搜索控件只能处理一种类型,我将父类型传递给它这是Person以便我可以在搜索中访问其所有子类型属性,但我遇到了上面提到的问题。 Any idea? 任何的想法?

When it comes to EF inheritance, the cast operator is not supported in LINQ to Entities query. 当涉及到EF遗传, cast运营商不支持LINQ到实体查询。 However, the is and as operator are perfectly supported, so the correct way of writing such filters is like this: 但是, isas操作符完全受支持,因此编写此类过滤器的正确方法如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM