代码之家  ›  专栏  ›  技术社区  ›  James

在运行时为EntityFramework中的GroupBy创建LINQ查询(带继承)

  •  2
  • James  · 技术社区  · 15 年前

    public class Foo
    {
      public string Color { get; set; }
    }
    
    public class Bar : Foo
    {
      public string Height { get; set; }
    }
    
    public class Pipe : Foo
    {
      public string Width { get; set; }
    }
    

    所以,我有很多Foo,这是我的基类,我希望能够指定一个属性,并执行以下查询:

       from e in Context.Foos
       group e.Color by e.Color into result
       select new
       {
     Value      = result.Key,
     ValueCount = result.Count()
       }
    

    最终结果应该是:

    黑色4 黄色2

    这是可行的,但是我想在运行时使用客户端传递的属性名“Color”来指定它。另外,我还想搜索派生实体。如果我试着

       group e.Height by e.Height into result
    

    它不起作用,因为在Foo里没有高度,只有在Bar里。但关键是我 要返回条,还应在运行时指定。这是我遇到的主要问题。我做不到 Foos.OfType<Bar>.GroupBy(some dynamic stuff)

    非常感谢你在这件事上的帮助。

    编辑

    基本上,我想做的是 System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Community CDub    7 年前

    this answer ,一个 func 用于创建动态 Where

    private List<T> GetResults<T>(IQueryable<T> source, 
       Expression<Func<T, bool>> queryFunction)
    {
       return source.Where(queryFunction).ToList<T>();
    }
    

    你应该能做类似的事情 GroupBy .