简体   繁体   English

使用Code-first Entity Framework过滤多个派生类

[英]Filter with multiple derived classes with Code-first Entity Framework

Lets say I have a User with 2 derived entities Student , Teacher . 假设我有一个带有2个派生实体的User StudentTeacher I used the TPH method, so I actually have no property at all in my classes to tell me who is a teacher or not. 我使用了TPH方法,所以在课堂上我根本没有任何属性可以告诉我谁是老师。

I have 2 booleans that should allow me to load either student or teacher such as this: 我有2个布尔应该允许我加载学生或老师,如下所示:

//IQueryable<User>
var query = userRepository.GetUsers();

//Type filtering
if (searchModel.IsStudent)
{
    query = query.OfType<Student>();
}
if (searchModel.IsTeacher)
{
    query = query.OfType<Teacher>();
}

When this tries to evaluate, I get this error when both are true: 当这个尝试评估时,当两者都为真时我得到这个错误:

DbIsOfExpression requires an expression argument with a polymorphic result type that is compatible with the type argument.

I already looked at some answers here on SO but they are geared towards 1 type of filtering. 我已经在SO上查看了一些答案,但它们适用于一种类型的过滤。

I would then like to do something like this (rough coding): 我想做这样的事情(粗略编码):

if(query.ToList().FirstOrDefault() is Student)
{
     print "student";
}

The mapping: 映射:

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

Try this one. 试试这个吧。 It works at least for EF 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);
}

This is ugly but it will work for what you need: 这很难看,但它可以满足您的需求:

if (searchModel.IsStudent && searchModel.IsTeacher) 
{
    var result = context.Users.OfType<Teacher>()
                        .Cast<User>()
                        .Union(context.Users.OfType<Student>());
}

And It will run on one query!! 它将在一个查询上运行!! :) :)

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

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