我正在开发一个 Asp.Net 的MVC应用程序,我是Linq和CodeFirst的新手。在我的控制器中,这是我编写的操作:
public ActionResult Filter(int? PaperType , int? PaperGram , int? Brand)
{
var FilteredResult ;
if (PaperType.HasValue && PaperGram.HasValue && Brand.HasValue) {
FilteredResult = db.Stocks.where(m => m.PaperType == PaperType && m.PaperGram == PaperGram && m.Brand == Brand);
}
else if (PaperType.HasValue && PaperGram.HasValue) {
FilteredResult = db.Stocks.where(m => m.PaperType == PaperType && m.PaperGram == PaperGram);
}
else if (PaperType.HasValue && Brand.HasValue) {
FilteredResult = db.Stocks.where(m => m.PaperType == PaperType && m.Brand == Brand);
}
// and ifs continue to last
/*
.
.
.
.
*/
else {
FilteredResult = db.Stocks;
}
return View(FilteredResult);
}
但我知道这不是在 Linq 和 Codefirst 中最好的方法。那么,你能给出一个更好的解决方案吗?
你可以这样做:
FilteredResult = db.Stocks.where(m => (m.PaperType == PaperType || !PaperType.HasValue)
&& (m.PaperGram == PaperGram || !PaperGram.HasValue)
&& (m.Brand == Brand || !Brand.HasValue));
您要避免的是代码重复。
创建您的原始 IQueriable,然后在必要时添加您的 where 子句
public ActionResult Filter(int? PaperType, int? PaperGram, int? Brand)
{
var FilteredResult FilteredResult = db.Stocks.AsQueryable();
if(PaperType.HasValue)
{
FilteredResult = FilteredResult.where(m => m.PaperType == PaperType);
if(PaperGram.HasValue)
FilteredResult = FilteredResult.where(m => m.PaperGram == PaperGram );
if ( Brand.HasValue)
FilteredResult = FilteredResult.where(m => m.Brand == Brand);
}
return View(FilteredResult);
}
您可以将所有元素分配给列表,然后过滤每个 if 条件中的每个元素
IEnumerable<Stock> filteredResult = db.Stocks.AsQueryable();
if (PaperType.HasValue)
{
filteredResult = filteredResult.Where(m => m.PaperType == PaperType);
}
if (PaperGram.HasValue)
{
filteredResult = filteredResult.Where(m => m.PaperGram== PaperGram);
}
if (Brand.HasValue)
{
filteredResult= filteredResult.Where(m => m.Brand== Brand);
}
return View(FilteredResult.ToList());