如何将此Linq SQL编写为动态查询(使用字符串)?

Zac*_*ott 6 c# linq repository linq-to-sql dynamicquery

根据需要跳到"特定问题".一些背景:

场景: 我有一组产品,其中包含一个填充了DDL的"向下钻取"过滤器(查询对象).每个渐进式DDL选择将进一步限制产品列表以及DDL的剩余选项.例如,从工具中选择锤子会限制产品尺寸仅显示锤子尺寸.

当前设置:我创建了一个查询对象,将其发送到存储库,并将每个选项提供给SQL"表值函数",其中空值表示"获取所有产品".

我认为这是一个很好的努力,但远非DDD可以接受.我想避免SQL中的任何"编程",希望用存储库做所有事情.对此主题的评论将不胜感激.

具体问题:

我如何将此查询重写为动态查询?像101 Linq Examples这样的链接会很棒,但是有一个动态查询范围.我真的想将这个方法传递给引号""中的字段,我想要一个选项列表以及有多少产品具有该选项.

from   p in db.Products
group  p by p.ProductSize into g
select new Category { 
       PropertyType = g.Key,
       Count = g.Count() }
Run Code Online (Sandbox Code Playgroud)

每个DDL选项都有"选择(21)",其中(21)是具有该属性的产品数量.选择一个选项后,所有其他剩余的DDL将使用剩余的选项和计数进行更新.

编辑:附加说明:

.OrderBy("it.City") // "it" refers to the entire record
.GroupBy("City", "new(City)") // This produces a unique list of City
.Select("it.Count()") //This gives a list of counts... getting closer
.Select("key") // Selects a list of unique City
.Select("new (key, count() as string)") // +1 to me LOL.  key is a row of group
.GroupBy("new (City, Manufacturer)", "City") // New = list of fields to group by
.GroupBy("City", "new (Manufacturer, Size)") // Second parameter is a projection

Product
.Where("ProductType == @0", "Maps")
.GroupBy("new(City)", "new ( null as string)")// Projection not available later?
.Select("new (key.City, it.count() as string)")// GroupBy new makes key an object

Product
.Where("ProductType == @0", "Maps")
.GroupBy("new(City)", "new ( null as string)")// Projection not available later?
.Select("new (key.City, it as object)")// the it object is the result of GroupBy

var a = Product
        .Where("ProductType == @0", "Maps")
        .GroupBy("@0", "it", "City") // This fails to group Product at all
        .Select("new ( Key, it as Product )"); // "it" is property cast though
Run Code Online (Sandbox Code Playgroud)

到目前为止我学到的是LinqPad很棒,但仍在寻找答案.最终,像我这样的完全随机的研究将占上风.大声笑.

编辑:

Jon Skeet有一个很棒的主意:投下我需要的东西IGrouping<string, Product>.感谢Jon Skeet!转换对象后,可以枚举集合并将结果提供给单独的列表.

goo*_*gic 4

我不确定如何使用查询语法(如上所述)来执行此操作,但是使用方法语法,我们可以使用 Expression<Func< ,如下所示。此示例适用于 AdventureWorks SQL Server 数据库(产品表),并允许您使用字符串指定要分组的列(在此示例中我选择了 Size)

using System;
using System.Linq;
using System.Linq.Expressions;

namespace LinqResearch
{
    public class Program
    {
        [STAThread]
        static void Main()
        {
            string columnToGroupBy = "Size";

            // generate the dynamic Expression<Func<Product, string>>
            ParameterExpression p = Expression.Parameter(typeof(Product), "p");

            var selector = Expression.Lambda<Func<Product, string>>(
                Expression.Property(p, columnToGroupBy),
                p
            );

            using (LinqDataContext dataContext = new LinqDataContext())
            {
                /* using "selector" caluclated above which is automatically 
                compiled when the query runs */
                var results = dataContext
                    .Products
                    .GroupBy(selector)
                    .Select((group) => new { 
                        Key = group.Key, 
                        Count = group.Count()
                    });

                foreach(var result in results)
                    Console.WriteLine("{0}: {1}", result.Key, result.Count);
            }

            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)