使用代码优先实体框架过滤多个派生类
假设我有一个 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>();
}
当尝试评估时,当两者都为 true 时,我会收到此错误:
DbIsOfExpression 需要一个具有与以下内容兼容的多态结果类型的表达式参数类型参数。
我已经在 SO 上查看了一些答案,但它们面向 1 种类型的过滤。
然后我想做这样的事情(粗略编码):
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"));
}
Lets say I have a User
with 2 derived entities Student
, Teacher
. 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.
I have 2 booleans that should allow me to load either student or teacher such as this:
//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.
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"));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个。它至少适用于 EF 5。
Try this one. It works at least for EF 5.
这很丑陋,但它可以满足您的需要:
并且它将在一个查询上运行! :)
This is ugly but it will work for what you need:
And It will run on one query!! :)