gpt4 book ai didi

mysql - 使用 LINQ 构建动态查询

转载 作者:行者123 更新时间:2023-11-29 08:40:38 25 4
gpt4 key购买 nike

我是rebuilding this website php/mysql 到 asp.net。我正在努力在页面标题中构建主卡片搜索表单。有一个文本输入、多个下拉菜单(全部指向不同的列)和一些条件搜索选项。

对于 mysql 版本,我能够使用条件来构建包含查询的字符串,然后执行它。

 //MySql/PHP example
$query = "SELECT * FROM cards WHERE ";

//Encounter_set
if (isset($_GET['Encounter_Set']){
$query.= "Encounter_Set=:Encounter_Set AND ";
$queryArray['Encounter_Set'] = $_GET['Encounter_Set'];
}

//radio statements
switch ($_GET['radio']) {
case "All": $query.= "(Title LIKE :terms OR Traits LIKE :terms OR Shadow_Text LIKE :terms OR Text LIKE :terms)";break;
case "Title": $query.= "(Title LIKE :terms)";break;
case "Traits": $query.= "(Traits LIKE :terms)";break;
case "Text": $query.= "(Shadow_Text LIKE :terms OR Text LIKE :terms)"; break;
default: $query.= "(Title LIKE :terms OR Traits LIKE :terms OR Shadow_Text LIKE :terms OR Text LIKE :terms)";
}

//Finally
$result = $db_con->prepare($query);

我该如何在 LINQ 中做到这一点?

最佳答案

using (var context = new MyDbContext())
{
IQueryable<Card> query = context.Cards;
if (!string.IsNullOrEmpty(Encounter_Set))
{
query = query.Where(c => c.Encounter_Set == Encounter_Set);
}
switch (radio)
{
default:
case "All":
query = query.Where(c => c.Title.Contains(terms)
|| c.Traits.Contains(terms)
|| c.Shadow_Text.Contains(terms)
|| c.Text.Contains(terms));
break;
case "Title":
query = query.Where(c => c.Title.Contains(terms));
break;
case "Traits":
query = query.Where(c => c.Traits.Contains(terms));
break;
case "Text":
query = query.Where(c => c.Shadow_Text.Contains(terms)
|| c.Text.Contains(terms));
break;
}
// ...
return query.ToList(); // Execute the query
}

关于mysql - 使用 LINQ 构建动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13894400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com