EF1:使用.oftype <>传递字符串值的过滤实体类的过滤类型
-
13-10-2019 - |
题
我有一种情况,我正在尝试使用派生的子类过滤LINQ选择。
ctx.BaseEntity.OfType<SubClass>()
- 这很好。
但是,我想使用字符串值来执行此操作。当我有很多(> 20)子类并在不使用oftype的情况下选择实体时,我遇到了性能障碍。我有一个通用的UI,可以从基类呈现,因此我不知道在编译时返回哪种类型。
所以我想做的是:
- 执行一个投影的选择,我只从数据库中返回子classtype
使用此值作为Oftype执行第二个选择,以仅从数据库中选择相关的实体(未生成质量工会)
int id = 1; var classType = (from c in ctx.BaseClass.Include("ClassType") where c.id == id select new { c.ClassType.TypeName }).First(); BaseClass caseQuery = ctx.BaseClass.OfType<classType.TypeName>() .Include("ClassType") .Include("ChildEntity1") .Include("ChildEntity2") .Where(x => x.id== id);
但是显然,由于type需要一种类型而不是字符串,因此这不起作用。
关于我如何实现这一目标的任何想法?
更新:作为原始问题的旁注,事实证明,当您投影使用导航属性的查询时,它也会构建怪物SQL,因此我最终使用了一个存储的过程来从基础上填充我的ClasStype实体ID。
解决方案
因此,我刚刚使用ESQL开始工作,我从未使用过。我在这里发布了代码,以防万一它可以帮助某人。还有其他人能想到的更强烈的解决方案吗?
BaseClass caseQuery = ctx.BaseClass.CreateQuery<BaseClass>("SELECT VALUE c FROM OFTYPE(Entities.[BaseClass],namespace.[" + classType.TypeName + "]) as c")
.Include("ClassType")
.Include("ChildEntity1")
.Include("ChildEntity2")
.Where(x => x.id== id).FirstOrDefault();
其他提示
回答有关打电话的标题问题 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 });
将其与您的存储过程结合使用以获取班级名称,您(应该?)避免了大量的加入 - 我没有每型式实现的实现,所以我无法测试。
不隶属于 StackOverflow