如何在Linq中编写以下SQL:
SELECT clientID, businessName
FROM clients
WHERE (regionID = CASE WHEN '{0}' = -1 THEN regionID ELSE '{0}' END)
ORDER BY businessName
这是我到目前为止所做的,但我不知道如何翻译where case语句:
var result = context.clients
.OrderBy(x => x.businessName)
.Select(x => new
{
x.clientID, x.businessName, x.active, x.regionID
})
.OrderBy(x=> x.businessName);
答案 0 :(得分:0)
尝试在查询中使用三元语句。我不确定它是否转换为SQL中的case语句,但你可以使用LINQPad来查找。
假设'val'包含将为{0} ...
插入的值var result = context.clients
.OrderBy(x => x.businessName)
.Select(x => new
{
x.clientID,
x.businessName,
x.active,
x.regionID == -1 ? val : x.regionID
})
.OrderBy(x=> x.businessName);
答案 1 :(得分:0)
假设您的变量被称为参数,您可以添加类似
的部分 .Where(a=>a.RegionID == ((parameter == -1) ? a.RegionID : parameter));
还有另一种方法可以通过构建像
这样的查询来避免使用case语句var query = context.clients.AsQueryable();
if (parameter != -1)
query = query.Where(a=>a.regionID == parameter);
var result = query
.OrderBy(x => x.Name )
.Select(x => new
{
x.clientID, x.businessName
});
如果参数为-1,则会产生类似
的内容SELECT clientID, businessName
FROM clients
ORDER BY businessName
否则会生成类似
的内容SELECT clientID, businessName
FROM clients
WHERE (regionID = parameter)
ORDER BY businessName