0

我的数据模型由 4 个表组成:项目引用产品、运输和用户。我想按产品字段对项目进行排序:类别和条件。在我的应用程序中,我使用 LINQ To SQL 类。这是我的代码:

public ViewResult Content(string category, string condition, int page = 1)
{
    var Items = _itemsRepository.GetItems()
                .Where(i => category == null && condition == null || 
                (i.Product.Category != null && i.Product.Category == category) ||
                (i.Product.Condition != null && i.Product.Condition == condition))
                .OrderBy(i => i.ItemId)
                .Skip((page - 1) * PageSize)
                .Take(PageSize)
                .Select(i => i);
     // return Items to the view
}

问题也可能是由路由引起的,所以这里是 global.asax 内容:

        // without categories and conditions
        routes.MapRoute(
            null,
            "Store/Content/Page{page}",
            new { controller = "Store", action = "Content", category = (string)null, condition = (string)null },
            new { page = @"\d+" });

        // with conditions
        routes.MapRoute(
            null,
            "Store/Content/{condition}/Page{page}",
            new { controller = "Store", action = "Content", category = (string)null },
            new { page = @"\d+" });

        // with categories
        routes.MapRoute(
            null,
            "Store/Content/{category}/Page{page}",
            new { controller = "Store", action = "Content", condition = (string)null },
            new { page = @"\d+" });

        // Default route
        routes.MapRoute(
            null,
            "{controller}/{action}",
            new { controller = "Home", action = "Index"});

如果我将带有类别的路线放在带有条件的路线之上,它可以按类别排序,反之亦然。如何同时按类别和条件排序?谢谢。

4

1 回答 1

0

这是一个经过优化的查询(顺便说一句,您没有按产品属性对项目进行排序 - 您正在过滤它们):

public ViewResult Content(string category, string condition, int page = 1)
{
    var Items = _itemsRepository.GetItems()
         .Where(i => ((category == null) || (i.Product.Category == category)) &&
                     ((condition == null) || (i.Product.Condition == condition)))
         .OrderBy(i => i.ItemId)
         .Skip((page - 1) * PageSize)
         .Take(PageSize)
         .Select(i => i);
    // return Items to the view
}

关于路由 - 正如我在评论中所说,您的类别路由无法执行。因此,如果类别和条件都是可选的,那么您可以传递一个参数,其中类别和条件由特殊字符分隔,或者两者都传递为category=foo&condition=bar.

还有一点 - 确保您的存储库在调用时不会将项目加载到内存中GetItems()

于 2013-01-05T13:54:17.337 回答