简体   繁体   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);
}

how i can neglect if price=0 from query means that it does not make any impact on EF query because if price=0 the query does not returning expected output.Because i have not any record that has 0 price so the query is always returning null . 如何,如果我可以忽略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();
}

i have tried like this it is working good but that is lengthy process.if i have 4 or 5 more variable that,s optional so it is necessary to check null value first for working.Any recommendation ? 我已经这样尝试过了,但是效果很好,但是这是一个漫长的过程。如果我有4或5个以上的变量是可选的,那么有必要首先检查null值是否起作用。有什么建议吗?

You can use the fllowing logic; 您可以使用以下逻辑:

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

What you can do is apply filters only if the condition holds. 您可以做的是仅在条件成立的情况下应用过滤器。 Let's say you need to check catName and price. 假设您需要检查catName和价格。 So: 所以:

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();

Obviously you'll need one "if" per filter, but it is much better than considering all possible combinations. 显然,每个过滤器需要一个“ if”,但这比考虑所有可能的组合要好得多。

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

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