sql 到具有 CASE 和子查询的 LINQ
sql to LINQ that has a CASE and a sub query
我一直在努力将下面的查询转换为 linq 查询,我非常接近,但我不确定如何将 case 语句添加到 LINQ。谷歌搜索让我如此接近。
原始工作查询:
SELECT *, CASE
WHEN Recipe_Name IN (SELECT Recipe_Name FROM Recipes WHERE Status = 2) THEN 0
ELSE 1
END AS editable
FROM Recipes WHERE Status = 1 ORDER BY Recipe_Name;
我的 LINQ - 缺少 case 语句:
var lcrecipes = from r in db.Recipes where r.Status == 2 select r.Recipe_Name;
var RecipeResults = from rr in db.Recipes where lcrecipes.Contains(rr.Recipe_Name) select rr;
我也试过:
var RecipeResults = from rr in db.Recipes
where lcrecipes.Contains(rr.Recipe_Name)
select new
{
editable = rr.Status == 2 ? "false" :
rr.Status == 1 ? "true" : ""
};
如何将 case 语句合并到 LINQ 中?任何朝着正确方向的推动将不胜感激
想想吧!
可编辑菜谱的状态不等于2,所以下面查询returns只有可编辑菜谱,满足你的需要;)你不需要任何子查询;)
var editablerecipes = from r in db.Recipes
where r.Status != 2
order r by r.Recipe_Name
select r.Recipe_Name;
如果您想添加可编辑字段,请使用:
var recipesWithEditableFlag = from r in db.Recipes
order r by r.Recipe_Name
select new {RecipeName= r.Recipe_Name, Editable = r.Status==2 ? "no" : "yes"};
对应的 SQL 应如下所示:
SELECT Recipe_Name, CASE WHEN Status = 2 THEN 'no' ELSE 'yes' END AS editable
FROM Recipes
ORDER BY Recipe_Name;
我一直在努力将下面的查询转换为 linq 查询,我非常接近,但我不确定如何将 case 语句添加到 LINQ。谷歌搜索让我如此接近。
原始工作查询:
SELECT *, CASE
WHEN Recipe_Name IN (SELECT Recipe_Name FROM Recipes WHERE Status = 2) THEN 0
ELSE 1
END AS editable
FROM Recipes WHERE Status = 1 ORDER BY Recipe_Name;
我的 LINQ - 缺少 case 语句:
var lcrecipes = from r in db.Recipes where r.Status == 2 select r.Recipe_Name;
var RecipeResults = from rr in db.Recipes where lcrecipes.Contains(rr.Recipe_Name) select rr;
我也试过:
var RecipeResults = from rr in db.Recipes
where lcrecipes.Contains(rr.Recipe_Name)
select new
{
editable = rr.Status == 2 ? "false" :
rr.Status == 1 ? "true" : ""
};
如何将 case 语句合并到 LINQ 中?任何朝着正确方向的推动将不胜感激
想想吧!
可编辑菜谱的状态不等于2,所以下面查询returns只有可编辑菜谱,满足你的需要;)你不需要任何子查询;)
var editablerecipes = from r in db.Recipes
where r.Status != 2
order r by r.Recipe_Name
select r.Recipe_Name;
如果您想添加可编辑字段,请使用:
var recipesWithEditableFlag = from r in db.Recipes
order r by r.Recipe_Name
select new {RecipeName= r.Recipe_Name, Editable = r.Status==2 ? "no" : "yes"};
对应的 SQL 应如下所示:
SELECT Recipe_Name, CASE WHEN Status = 2 THEN 'no' ELSE 'yes' END AS editable
FROM Recipes
ORDER BY Recipe_Name;