1

我其中我试图筛选LINQ选择使用派生的子类的情况下过滤派生类型实体类的。EF1:使用.OfType <>通过使一个字符串值

ctx.BaseEntity.OfType<SubClass>() - 这工作得很好。

但是我想用字符串值代替。当我有很多(> 20)Sub Classes并选择实体而不使用OfType时,我遇到了性能障碍,这不是一种选择。我有一个从基类呈现的通用UI,所以我不知道在编译时将返回什么类类型。

所以我想要做的是这样的:

  1. 执行投射选择,我 从 只返回SubClassType数据库
  2. 执行使用这个值作为第二选择 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); 
    

但显然这是行不通的,因为OfType需要一个类型,而不是一个字符串。

关于我如何实现这一点的任何想法?

更新: 作为一个侧面说明原来的问题,事实证明那一刻你的项目使用导航属性查询 - 它建立怪物SQL太多,所以我已经结束了使用存储过程从BaseClass Id填充我的ClassType实体。

回答

1

所以我刚刚才使用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(); 
0

要回答这个标题问题有关调用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 }); 

与存储过程一起使用能获取类的名字,你(应该?)避免大量连接 - 我没有每种类型的实现来玩,所以我无法测试。

相关问题