根据需要跳到“特定问题”。一些背景:
场景:我有一组产品,这些产品带有填充了DDL的“向下钻取”过滤器(查询对象)。每个渐进式DDL选择将进一步限制产品列表以及DDL剩余的选项。例如,从工具中选择锤子会将“产品尺寸”限制为仅显示锤子尺寸。
当前设置:我创建了一个查询对象,将其发送到存储库,并将每个选项提供给SQL“表值函数”,其中空值表示“获取所有产品”。
我认为这是一个很好的尝试,但DDD尚不能接受。我想避免在SQL中进行任何“编程”,希望对存储库进行所有操作。对此主题的评论将不胜感激。
具体问题:
我将如何将该查询重写为Dynamic Query?链接到101 Linq Examples之类的链接非常棒,但是具有动态查询范围。我真的很想将带有引号“”的字段传递给此方法,为此我需要一个选项列表以及有多少个产品具有该选项。
from p in db.Products
group p by p.ProductSize into g
select new Category {
PropertyType = g.Key,
Count = g.Count() }
每个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
到目前为止,我了解到的是LinqPad非常棒,但仍在寻找答案。最终,我猜想像这样的完全随机研究将占上风。哈哈。
编辑:
乔恩·斯基特(Jon Skeet)有一个绝妙的主意:将我需要的内容转换为
IGrouping<string, Product>
。感谢乔恩·斯基特(Jon Skeet)!转换对象后,您可以枚举集合并将结果输入到单独的列表中。 最佳答案
我不确定如何使用查询语法(如上所述)执行此操作,但是使用方法语法,我们可以使用Expression
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();
}
}
}
关于c# - 如何将此Linq SQL编写为动态查询(使用字符串)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2531679/