Entity Framework :按子类型的 属性 过滤查询

Entity Framework : Filter query by property of a child type

我有如下模型

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; }
}

现在我想通过 Employee 的 属性 查询 Person 如下

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

但是我得到以下错误

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

我知道我可以简单地使用

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

但问题是我使用的是通用搜索控件,该控件只能处理一种要搜索的类型,搜索条件作为该确定类型的 lambda 表达式传递给该控件,并且还返回搜索语句通过搜索控件作为 lambda 表达式,然后作为谓词传递给 Where 方法,现在我想使用此搜索控件同时搜索 EmployeePerson,并且由于搜索控件只能处理一种类型,因此我将父类型传递给它 Person 以便我可以在搜索中访问其所有子类型属性,但我遇到了上述问题。有什么想法吗?

涉及 EF 继承时,LINQ to Entities 查询不支持 cast 运算符。但是,isas 操作符是完美支持的,所以这种过滤器的正确写法是这样的:

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