我正在尝试使用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);
}
那么请告诉我这三种方法有什么区别,请向我解释为什么#2和#3不起作用?
答案 0 :(得分:4)
product.Where(s => s.SubID == SubID);
...不会在产品上添加条件,它只会在应用条件的情况下创建一个IEnumerable,并立即将其抛弃。你想要的可能是什么;
product = product.Where(s => s.SubID == SubID);