繁体   English   中英

条件C#中实体框架中查询的忽略变量

[英]Neglect variable from Query in entity framework where condition C#

public ActionResult sortFilteredItem(string sortByValue,string brand,string category,int price=0 )
{
  var sortedData = (dynamic)null;
  if (sortByValue != "")
  {
    if(sortByValue == "ltoh")
    {
      sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category & x.price == price).ToList();
    }

  }
 return View(sortedData);
}

如何,如果我可以忽略price=0 ,从查询意味着它不会对EF查询的任何影响,因为如果price=0查询并没有返回预期output.Because我还没有有0任何记录price ,因此查询总是返回null

if(price != 0)
{
    sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category & x.price == price).ToList();
}
else
{
    sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category).ToList();
}

我已经这样尝试过了,但是效果很好,但是这是一个漫长的过程。如果我有4或5个以上的变量是可选的,那么有必要首先检查null值是否起作用。有什么建议吗?

您可以使用以下逻辑:

sortedData = DB.Prouducts.where(x=> x.brandName == brand 
    && x.catName == category 
    && (price == 0 || x.price == price)) //use this approach for every optional param
    .ToList();

您可以做的是仅在条件成立的情况下应用过滤器。 假设您需要检查catName和价格。 所以:

var query = DB.Prouducts.Where(x=> x.brandName == brand);
if (category != null)
{
     query = query.Where(x => x.catName == category);
}

if (price != 0)
{
    query = query.Where(x => x.price == price)
}

sortedData = query.ToList();

显然,每个过滤器需要一个“ if”,但这比考虑所有可能的组合要好得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM