0

我正在尝试使用 MVC3 实现结果过滤器并遇到这样的问题:

 public ActionResult  Index(int? SubID)
    {
        var product = db.Product.Where(s => s.SubID == SubID).Include(t => t.SubCategory);

        if (SubID.HasValue)
        {
            ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);                
        }
        else
        {
            ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");                
        }



        return View(product);
    }

上面的这个工作正常,但下面的总是给我整个表的结果,不管我把它放在什么条件下:

public ActionResult  Index(int? SubID)
    {
        var product = db.Product.Include(t => t.SubCategory);

        if (SubID.HasValue)
        {
            ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);                
            product.Where(s => s.SubID == SubID);
        }
        else
        {
            ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");                
        }



        return View(product);
    }

甚至这个也不起作用:

public ActionResult  Index(int? SubID)
        {
            var product = from m in db.Product
                          select m;

            if (SubID.HasValue)
            {
                ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);                
                product.Where(s => s.SubID == SubID);
            }
            else
            {
                ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");                
            }

            product.Include(t => t.SubCategory);

            return View(product);
        }

所以请告诉我这 3 种方法有什么区别,请向我解释为什么 #2 和 #3 不起作用?

4

1 回答 1

4
product.Where(s => s.SubID == SubID);

...不会在产品上添加条件,它只是创建一个应用了条件的 IEnumerable,然后立即将其丢弃。你想要的可能是;

product = product.Where(s => s.SubID == SubID);
于 2013-06-02T21:24:24.983 回答