【问题标题】:Create LINQ query at runtime to GroupBy in EntityFramework (with inheritance)在运行时创建 LINQ 查询到 EntityFramework 中的 GroupBy(具有继承)
【发布时间】:2010-01-11 19:29:22
【问题描述】:

这就是场景。我有以下三个类,它们是在实体框架中定义的,我这里只定义它们作为示例:

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()
   }

最后应该是:

蓝色 2 黑4 黄色 2

这可行,但是我想在运行时指定它,使用客户端传递的属性名称“颜色”。另外,我也想搜索派生实体。如果我尝试做

   group e.Height by e.Height into result

它不会起作用,因为 Foo 中没有高度,只有 Bar 中。但重点是我仅想要返回 Bars,这也应该在运行时指定。这是我一直遇到的主要问题。我不能Foos.OfType<Bar>.GroupBy(some dynamic stuff) 因为我不知道在运行时要过滤的类型。

非常感谢您对此事的帮助。

编辑

基本上,我想做的是System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>),但最后返回 Count 而不是 Sum。

【问题讨论】:

    标签: c# linq entity-framework lambda


    【解决方案1】:

    在this answer 中,func 用于创建动态Where。

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

    你应该可以用GroupBy做类似的事情。

    【讨论】:

    • 这不起作用,因为您必须传入一个完全类型化的 Func。但是在这里我直到运行时才知道要搜索的对象的类型。
    • 您可以决定在运行时传入哪个全类型函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多