【问题标题】:can anyone advice with getting count for amount of products in category for specified results with linq任何人都可以建议使用 linq 计算类别中指定结果的产品数量
【发布时间】:2012-01-26 02:07:40
【问题描述】:

我创建了一组搜索结果,我希望创建一个可用猫的过滤器,以及该过滤器中的结果数量。但是在尝试执行此操作时,我遇到了最奇怪的错误。

Unable to create a constant value of type 'NAMESPACE.Models.Products'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

这是我尝试过的代码:

var cats = (from p in ctx1.SubCategories
                        where myCats.Contains(p.subCategoryId) && p.enabled
                        select new
                            AvailableSubCats
                                   {
                                       CategoryName = p.subCategoryName,
                                       Id = p.subCategoryId,
                                       TotalItems = model.Count(x => x.subCategoryId == p.subCategoryId)
                                   }).Distinct();

Products 是在totalItems 行中称为模型的对象。 我也试过这个:

var cats = from c in ctx1.SubCategories
                       join p in model on c.subCategoryId equals p.subCategorySubId
                       group p by c.subCategoryName
                       into g
                       select new
                           AvailableSubCats
                                  {
                                      CategoryName = g.Key,
                                      Id = 0,
                                      TotalItems = g.Count()
                                  };

同样的错误,不喜欢这样,因为我不知道如何获取类别的名称及其 ID。

非常感谢您的帮助。

谢谢

p.s 我正在使用实体框架 4.1、.net 4 和 MVC 3、mysql

简而言之,我正在尝试在 linq 中运行它,但是产品方面已经是结果

select c.*, (select count(productId) from Products where Products.subCategoryId = c.subCategoryId) as counter  from SubCategories c

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 entity-framework linq-to-sql


    【解决方案1】:

    您可以尝试将您的产品列表转换为 subCategoryId 的列表,以便 EF 能够理解它。比如:

    var subCategoryIds = model.Select(m => m.subCategoryId);
    
    var cats = (from p in ctx1.SubCategories
    ctx1.SubCategories
    where myCats.Contains(p.subCategoryId) && p.enabled
    select new
        AvailableSubCats
        {
            CategoryName = p.subCategoryName,
            Id = p.subCategoryId,
            TotalItems = subCategoryIds.Count(x => x == p.subCategoryId)
        }).Distinct();
    

    【讨论】:

    • 我做不到,我或多或少有这个价值,我称之为 myCats,但我无法运行它,因为它会产生错误 {"Too high level of nesting for select"} ,如果可能的话,需要更简单
    • 是的 mysql 服务器,似乎是一个 mysql 唯一的错误,我知道它很脏但已经循环通过猫,然后放入临时列表,然后返回临时列表 asQueryable 似乎是唯一的方法:-|
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多