【问题标题】:sql to LINQ that has a CASE and a sub query具有 CASE 和子查询的 sql to LINQ
【发布时间】:2015-04-07 19:13:05
【问题描述】:

我一直在努力将下面的查询转换为 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 - 缺少案例陈述:

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 中?任何朝着正确方向的推动将不胜感激

【问题讨论】:

标签: c# linq asp.net-mvc-3 subquery case


【解决方案1】:

想一想!

可编辑菜谱的状态不等于 2,因此下面的查询仅返回可编辑菜谱,满足您的需求;)您不需要任何子查询;)

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;

【讨论】:

  • 我的错误,我想要可编辑和不可编辑的食谱,只有一个字段是一个标志,如果有或没有。我将尝试您的查询,谢谢。
  • 感谢您的帮助,我遇到了左右错误,所以在我整理它们之前我不确定它是否有效。我会及时通知你
  • 什么样的错误?哪条线?尝试删除order r by r.Recipe_Name 并检查结果。
  • 感谢您的帮助,我最终使用了原始查询的数据库视图并将 LINQ 用作:from r in db.v_recipes。我接受了你的回答,因为你确实帮助我完成了 90% 的工作
  • 很高兴能帮到你;)
猜你喜欢
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
相关资源
最近更新 更多