gpt4 book ai didi

c# - 将条件构建的 SQL where 子句转换为 LINQ

转载 作者:行者123 更新时间:2023-11-30 22:48:10 25 4
gpt4 key购买 nike

所以我在这里没有看到真正回答这个问题的问题。这是一个关于 linq 的新手问题,但我想知道是否可以将以下 sql 查询(使用 C# 构建)转换为 linq 查询:

public void DoSomeQuery(bool whereCriteria1, bool whereCriteria2)
{
string sqlQuery = "SELECT p.*";
string fromClause = " FROM person p";
string whereClause = " WHERE ";

if (whereCriteria1)
{
fromClause += ", address a";
whereClause += " p.addressid = a.addressid and a.state = 'PA' and a.zip = '16127' "
}

if (whereCriteria2)
{
fromClause += ", color c";
whereClause += " p.favoritecolorid = c.colorid and c.name = 'blue'"
}

// arbitrarily many more criteria if blocks could be here

sqlQuery += fromClause + whereClause;

// do stuff to run the query
}

这有意义吗?我有一堆 bool 变量,让我知道要添加哪个 where 子句条件。我想在 linq 中这样做,因为...这很丑陋。

最佳答案

var query = from p in persons select p;
if (whereCriteria1)
{
query = from p in query
join a in address on p.addressid equals a.addressid
where a.state = 'PA'
where a.zip = '16127'
select p;
}
if (whereCriteria2)
{
query = from p in query
join c in colors on p.favoritecolorid equals c.colorid
where c.name = 'blue'
select p;
}

关于c# - 将条件构建的 SQL where 子句转换为 LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1849005/

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