可以说我有一个带有2个派生实体UserStudentTeacher。我使用了TPH方法,所以实际上我的课上根本没有任何属性可以告诉我谁是老师。

我有2个 bool 值,应允许我加载学生或老师,例如:

//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"));
    }

最佳答案

试试这个。它至少适用于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);
}

关于c# - 使用代码优先 Entity Framework 过滤多个派生类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7897327/

10-10 23:27