Ef和MVC中的if-else语句
c#
我有三个字段,我想根据它们过滤我的结果。我用了一个 if-else 语句,但它很尴尬,根据我的领域,我不得不写一些 if blocks 语句。有没有更简单的方法来做到这一点?
public ActionResult Search(String title, int? category_id, string productCode)
{
IEnumerable<products> result;
using (DBModels db = new DBModels())
{
if (title != null && category_id == null && productCode == null)
{
result = db.products.Where(c => c.title.Contains(title))
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
return View(result);
}
else if (category_id != null && title == null && productCode == null)
{
result = db.products.Where(c => c.category_id == category_id)
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
return View(result);
}
else if (productCode != null && title == null && category_id == null)
{
result = db.products.Where(c => c.id.ToString().Contains(productCode))
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
return View(result);
}
else if (productCode != null && title != null && category_id != null)
{
result = db.products.Where(c => c.title.Contains(title)
&& c.category_id == category_id
&& c.id.ToString().Contains(productCode))
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
}
}
result = db.products.Where(c => c.title.Contains(title)
|| c.category_id == category_id
|| c.id.ToString().Contains(productCode))
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
return View(result);
}
回答
您可以使用 IQueryable
public ActionResult Search(string title, int? category_id, string productCode)
{
IEnumerable<products> result;
using (DBModels db = new DBModels())
{
var query = db.products
.Include(x => x.media)
.Include(p => p.categories)
.AsQueryable();
if (!string.IsNullOrWhiteSpace(title))
{
query = query.Where(c => c.title.Contains(title));
}
if ( category_id != null)
{
query = query.Where(c => c.category_id == category_id);
}
if (!string.IsNullOrWhiteSpace(productCode))
{
query = query.Where(c => c.id.ToString().Contains(productCode));
}
result = query.ToList();
return View(result);
}
}