根据条件检索类别及其关联产品

时间:2011-09-08 02:18:38

标签: asp.net-mvc asp.net-mvc-3 entity-framework-4.1

我有一个MVC应用程序,我正在创建基于MVC音乐商店教程,而不是音乐商店,我正在建立一个时尚&服装店。我更改了部分视图以显示品牌(MusicStore上的艺术家)和类别(类型),并且必须按性别过滤产品。我尝试了不同的方法,但没有任何接近我的期望。

以下是StoreController的示例:

    public ActionResult Brand(int cod)
    {
        // Retrieve Brand and its associated Products from database
        var brandModel = storeDB.Brands.Include("Products")
            .Single(g => g.BrandId == cod);

        return View(brandModel);
    }

我想尝试这样的事情:

  

/商店/浏览/曼?类型= 1个
  /存储/浏览/女人?类型= 1个
  /存储/浏览/人?品牌= 1个
  /商店/浏览/女人?品牌= 1个

菜单将是......

  • 女人
    • 按风格浏览
      • [类别]
    • 按品牌浏览
      • [BRANDS]
    • 按风格浏览
      • [类别]
    • 按品牌浏览
      • [BRANDS]

品牌可以为两种性别提供产品,但是当从/Man?Brand=1浏览时,它应该仅显示男士服装,如果品牌只有女士服装,则不应在Man / Browse by Brand菜单上列出该品牌。

我需要在ActionResults上更改以验证Products表上的Gender列吗?

1 个答案:

答案 0 :(得分:0)

如果我们使用以下简化模型:

public class Brand
{
    public int BrandId { get; set; }
    public string BrandName { get; set; }
    // other properties
}

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    // other properties
}

public class Product
{
    public int ProductId { get; set; }
    public int BrandId { get; set; }
    public int CategoryId { get; set; }
    public string ProductGender { get; set; }
    // other properties
}

然后我们可以按如下方式创建性别特定类别:

<强>已更新

var womenByStyle = (from p in _db.Products where p.ProductGender == "Female"
    join c in _db.Categories on c.CategoryId equals p.CategoryId
    select c.CategoryId, c.CategoryName).Distinct();

var womenByBrand = (from p in _db.Products where p.ProductGender == "Female"
    join b in _db.Brand on b.BrandId equals p.BrandId
    select b.BrandId, b.BrandName).Distinct();

我们可以在我们的查询字符串中进行特定搜索(例如Man?Brand=1),如下所示:

public ActionResult Man(int? Brand, int? Style)
{
    if (Brand != null)
    {
        var brandProductsForMale = from p in _db.Products 
            where p.ProductGender == "Male" && BrandId == Brand;

        // map to ViewModel

        return View("Products", brandProductsForMaleModel);
    }

    // et cetera
}
相关问题