在Asp中同时按2个条件过滤项时出现问题.Net MVC 3与LINQ To SQL数据模型



我的数据模型由4个表组成:Item引用Product, Shipping和User。我想按产品字段:类别和条件对项目进行排序。在我的应用程序中,我使用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
}

这个问题也可能是由路由引起的,所以这里是全局的。目录:

        // 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"});

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

这里是一个小优化查询(顺便说一句,你不是按产品属性排序项目-你是过滤它们):

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()

时,请确保存储库不会在内存中加载项。

最新更新