最佳实践:将属性添加到LINQ to Entities查询结果中

本文关键字:to LINQ Entities 查询 结果 添加 属性 最佳 | 更新日期: 2023-09-27 18:22:46

我正在编写一个ASP.NET Web Pages应用程序,其中有一个庞大的LINQ to Entities查询。此查询从数据库中的表中提取数据,对其进行筛选,对数据进行两次分组,并向结果集添加额外的属性。然后,我循环遍历该表,输出行。

查询量很大,对不起:

accountOrders = db.EventOrders
    .Where(order => order.EventID == eventID)
    .OrderBy(order => order.ProductCode)
    .GroupBy(order => new { order.AccountNum, order.Exhibitor, order.Booth })
    .Select(orders => 
        new {
            Key = orders.Key,
            ProductOrders = orders
                .GroupBy(order => new { order.ProductCode, order.Product, order.Price })
                .Select(productOrders => 
                    new {
                        Key = productOrders.Key,
                        Quantity = productOrders.Sum(item => item.Quantity),
                        HtmlID = String.Join(",", productOrders.Select(o => (o.OrderNum + "-" + o.OrderLine))),
                        AssignedLines = productOrders.SelectMany(order => order.LineAssignments)
                    })
        })
        .Select(account => 
            new { 
                Key = account.Key,
                // Property to see whether a booth number should be displayed
                HasBooth = !String.IsNullOrWhiteSpace(account.Key.Booth),
                HasAssignedDigitalLines = account.ProductOrders.Any(order => order.AssignedLines.Any(line => line.Type == "digital")),
                // Dividing the orders into their respective product group
                PhoneOrders      = account.ProductOrders.Where(prod => ProductCodes.PHONE_CODES.Contains(prod.Key.ProductCode)),
                InternetOrders   = account.ProductOrders.Where(prod => ProductCodes.INTERNET_CODES.Contains(prod.Key.ProductCode)),
                AdditionalOrders = account.ProductOrders.Where(prod => ProductCodes.ADDITIONAL_CODES.Contains(prod.Key.ProductCode))
            })
        .ToList();

我使用添加的属性来帮助设置输出的样式。例如,我使用HasBooth属性来检查是否应该在参展商名称旁边的括号中输出展位位置。问题是我必须将这个大查询保存为IEnumerable,这意味着我得到了错误:如果不首先将lambda表达式强制转换为委托或表达式树类型,就无法将其用作动态调度操作的参数我应该以这种方式处理查询吗?

非常感谢您的任何建议!

最佳实践:将属性添加到LINQ to Entities查询结果中

在某个时刻,您将向方法传递一个动态数据类型,这反过来又将返回类型更改为简单的dynamic。您可以将动态类型强制转换为在编译时可识别的类型,也可以显式设置返回类型,而不使用var

您可以在此处阅读有关此问题的更多信息:http://www.mikesdotnetting.com/Article/198/Cannot-use-a-lambda-expression-as-an-argument-to-a-dynamically-dispatched-operation