【问题标题】:Navigation by category in app with compound entity model in asp.net mvc 3在 asp.net mvc 3 中使用复合实体模型在应用程序中按类别导航
【发布时间】:2012-12-12 14:46:40
【问题描述】:

我需要按类别过滤产品并提供每个类别的链接。
这是来自 StoreController 的方法:

public ViewResult Content(string category = null, int page = 1)
    {
        var model = new StoreContentViewModel
            {
                Items = _itemsRepository.GetItems()
                .Where(i => i.Product.Category == category || i.Product.Category == null)
                .OrderBy(i => i.ItemId)
                .Skip((page-1)*PageSize)
                .Take(PageSize),

                PageInfo = new PageInfo
                    {
                        TotalItems = category == null ? _itemsRepository.GetItems().Count() :
                        _itemsRepository.GetItems().Where(i => i.Product.Category == category).Count(),
                        CurrentPage = page,
                        ItemsPerPage = PageSize
                    },

                CurrentCategory = category
            };
        return View(model);
    }

这是来自 NavigationController 的方法:

    public PartialViewResult Menu(string category)
    {
        ViewBag.SelectedCategory = category;

        IEnumerable<string> result = _itemsRepository.GetItems()
                                     .Select(i => i.Product.Category)
                                     .Distinct()
                                     .OrderBy(i => i);

        return PartialView(result);
    }

此菜单方法的部分视图:

@model IEnumerable<string>

@Html.ActionLink("All products", "Content", "Store")

@foreach (var link in Model)
{
@Html.RouteLink(link,
   new
   {
       controller = "Navigation",
       action = "Menu",
       category = link,
       page = 1
   },
   new
   {
       @class = link == ViewBag.SelectedCatgory ? "selectedLink" : null
   }
   )

}

在我的模型中,1 个项目包含 1 个产品(ProductId 是 Items 表中的外键)。当我运行应用程序时,我收到一个错误:“该值不能等于 null 或空。参数名称:controllerName”。此操作方法的单元测试也失败了。
不添加类别过滤一切正常。

我认为问题在于我从 _itemsRepository 获取“类别”属性的行,(导致“过滤器”单元测试也失败):

_itemsRepository.Product.Category  

对吗?如果是我想知道是否有其他方法可以访问“类别”属性??
提前致谢。

编辑:
消息错误是由错误的路由引起的。
仍然无法按类别选择项目,问题肯定与此行有关:

Items = _itemsRepository.GetItems()
                .Where(i => i.Product.Category == category || i.Product.Category == null)

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3 linq entity-relationship


    【解决方案1】:

    您是否使用实体框架作为您的 ORM?如果是这样,实体框架不会自动为您加载相关对象。你必须告诉它你想要加载对象。您可以通过使用 Include() 方法急切地加载您的属性来做到这一点。看看我对这个问题的回答。非常相似。

    How to access child entity's property in a where clause of linq expression?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      相关资源
      最近更新 更多