我想按类别显示项目。我使用linq,一切正常,除了我不能显示所有项目,无论类别。可能是路由问题,因为我已经问过我使用的linq表达式的问题,它应该没问题。无论如何,这是我的代码:
public ViewResult Content(string category, int page = 1)
{
var model = new StoreContentViewModel
{
Items = _itemsRepository.GetItems()
.Where(i => i.Product.Category == null ||
i.Product.Category != null && i.Product.Category == category)
.OrderBy(i => i.ItemId)
.Skip((page - 1) * PageSize)
.Take(PageSize)
.Select(i => i),
}
}
RegisterRouts方法的内容:
// without categories
routes.MapRoute(
null,
"Store/Content/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" },
new { page = @"\d+" });
// Default route
routes.MapRoute(
null,
"{controller}/{action}",
new { controller = "Home", action = "Index"});
我对“有和无类别”路线的顺序感到困惑。
当我输入网址时:
~/Store/Content
或:
~/Store/Content/Page1 // or Page2
不显示项目。但如果我进入:
~/Store/Content/Man's-Shoes/Page1
显示与“男士鞋”类别相关联的项目。
那么,这个问题与溃败或mabby有关还有另外一个问题吗?
P.S。我过去2天一直在处理这个问题,所以任何帮助都是合适的。
编辑:
而且这个单元测试失败了。可能写得很糟糕。检查一下。
在我的模型中,我有Items实体“包含”产品和运输实体:
[TestMethod]
public void Can_Filter_Content()
{
//Arrange
private Mock<IItemsRepository> _itemsMock = new Mock<IItemsRepository>();
private Mock<IProductRepository> _productsMock = new Mock<IProductRepository>();
private Mock<IShippingRepository> _shippingMock = new Mock<IShippingRepository>();
_itemsMock.Setup(i => i.GetItems()).Returns(new[]
{
new Item { ItemId = 1, ProductId = 1, ShippingId = 1},
new Item { ItemId = 2, ProductId = 2, ShippingId = 2},
new Item { ItemId = 3, ProductId = 3, ShippingId = 3},
new Item { ItemId = 4, ProductId = 4, ShippingId = 4}
});
_productsMock.Setup(p => p.GetProducts()).Returns(new[]
{
new Product { ProductId = 1, Category = "shoes"},
new Product { ProductId = 2, Category = "shoes"},
new Product { ProductId = 3, Category = "superShoes"},
new Product { ProductId = 4, Category = "shoes"}
});
var controller = new StoreController(_itemsMock.Object,
_productsMock.Object, _shippingMock.Object) {PageSize = 2};
// Act
Item[] result = ((StoreContentViewModel) controller.Content(null).Model).Items.ToArray();
ViewResult viewResult = controller.Content(null);
// Assert
Assert.IsTrue(result[0].ItemId == 1 && result[1].ItemId == 2);
Assert.AreEqual(result.Length, 2);
Assert.AreEqual("", viewResult.ViewName);
}
Mabby这有帮助
答案 0 :(得分:1)
应该这样:
.Where(i => i.Product.Category == null ||
i.Product.Category != null && i.Product.Category == category)
是这样的:
.Where(i => category == null ||
i.Product.Category != null && i.Product.Category == category)
当category为null时,原始条件表示产品类别不为null的位置,并且该类别匹配null,这将永远不会起作用。新条件表示如果类别为null,则不评估条件;否则,匹配类别(“男士鞋子”)。