假设我有User
个带有2个派生实体Student
,Teacher
。我使用了TPH方法,所以在课堂上我根本没有任何属性来告诉我谁是老师。
我有2个布尔应该允许我加载学生或老师,如:
//IQueryable<User>
var query = userRepository.GetUsers();
//Type filtering
if (searchModel.IsStudent)
{
query = query.OfType<Student>();
}
if (searchModel.IsTeacher)
{
query = query.OfType<Teacher>();
}
当这个尝试评估时,当两者都为真时我得到这个错误:
DbIsOfExpression requires an expression argument with a polymorphic result type that is compatible with the type argument.
我已经在SO上查看了一些答案,但它们面向一种过滤方式。
我想做这样的事情(粗略编码):
if(query.ToList().FirstOrDefault() is Student)
{
print "student";
}
映射:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.Map<Teacher>(m => m.Requires("UserType").HasValue("Teach"))
.Map<Student>(m => m.Requires("UserType").HasValue("Stu"))
.Map<Staff>(m => m.Requires("UserType").HasValue("Staff"));
}
答案 0 :(得分:5)
试试这个。它至少适用于EF 5。
IQueryable<User> Filter(this IQueryable<User> query,
bool includeTeacher, bool includeStudent)
{
return query.Where(x => includeTeacher && x is Teacher
|| includeStudent && x is Student);
}
答案 1 :(得分:1)
这很难看,但它可以满足您的需求:
if (searchModel.IsStudent && searchModel.IsTeacher)
{
var result = context.Users.OfType<Teacher>()
.Cast<User>()
.Union(context.Users.OfType<Student>());
}
它将在一个查询上运行!! :)