How to write this Linq SQL as a Dynamic Query (using strings)?

后端 未结 2 1408
别跟我提以往
别跟我提以往 2021-01-02 21:36

Skip to the \"specific question\" as needed. Some background:

The scenario: I have a set of products with a \"drill down\" filter (Query Object) p

相关标签:
2条回答
  • 2021-01-02 21:47

    If you take a look at C# Bits, the author discusses how to create cascading filters using Dynamic Data. It does not sound like you are using Dynamic Data, but he does have a nice expression builder that might be helpful to you. See BuildQueryBody, and then the following section of extension methods on Iqueryable.

    Since you are not using Dynamic Data, you will need to deal with not having access to a "MetaForeignKeyColumn" object, but I suspect his approach might help you with your question.

    I hope this helps.

    0 讨论(0)
  • 2021-01-02 22:10

    I'm not sure how to do this using Query syntax (as above), but using Method syntax, we can use an Expression<Func< as shown below. This sample works against the AdventureWorks SQL Server database (Products table), and allows you to specify which column to group by using a string (in this sample I have chosen 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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题