EF1:使用 .OfType<> 过滤实体类的派生类型通过传递字符串值
我遇到了一种情况,我试图使用派生子类来过滤 LINQ 选择。
ctx.BaseEntity.OfType
- 这工作正常。
不过,我想使用字符串值来完成此操作。当我有很多(> 20)子类并且不使用 OfType 选择实体时,我遇到了性能障碍。我有一个从基类呈现的通用 UI,因此我不知道在编译时将返回什么类类型。
所以我想做的是:
- 执行投影选择我所在的位置 仅返回子类类型 数据库
执行第二次选择 使用该值作为 OfType 来 只选择相关的相关 数据库中的实体(无质量 生成工会)
int id = 1; var classType = (来自 ctx.BaseClass.Include("ClassType") 中的 c) 其中 c.id == id 选择新的 { c.ClassType.TypeName })。第一的(); BaseClass caseQuery = ctx.BaseClass.OfType
() .include("类类型") .include("ChildEntity1") .include("ChildEntity2") .Where(x => x.id== id);
但显然这不起作用,因为 OfType 需要类型而不是字符串
关于如何实现这一目标有什么想法吗?
更新: 作为原始问题的旁注,事实证明,当您项目使用导航属性的查询时,它也会构建怪物 SQL,因此我最终使用存储过程从 BaseClass 填充我的 ClassType 实体ID。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
相思故 2024-10-19 23:40:18
要回答有关使用字符串/运行时类型调用 OfType
的标题问题,您可以执行以下操作:
// Get the type, assuming the derived type is defined in the same assembly
// as the base class and you have the type name as a string
var typeToFilter = typeof(BaseClass)
.Assembly
.GetType("Namespace." + derivedTypeName);
// The use reflection to get the OfType method and call it directly
MethodInfo ofType = typeof(Queryable).GetMethod("OfType");
MethodInfo ofTypeGeneric = method.MakeGenericMethod(new Type[] { typeToFilter });
var result = (IQueryable<Equipment>)generic.Invoke(null, new object[] { equipment });
将其与存储过程结合起来以获取类名,并且您(应该?)避免大量连接 -我没有每个类型的表实现可供使用,所以我无法测试。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
所以我刚刚使用 eSQL 让它工作,而我以前从未使用过它。我在这里发布了代码,以防它对某人有帮助。还有其他人有他们能想到的更强类型的解决方案吗?
So I've just got it to work using eSQL, which I'd never used before. I've posted the code here just in case it helps someone. Has anyone else got a more strongly typed solution they can think of?