【问题标题】:sql case statement in where clause in linqlinq中where子句中的sql case语句
【发布时间】:2013-11-27 07:35:44
【问题描述】:

这是我的字符串 sql 查询,但我无法将其转换为 linq,因为它包含基于 where 子句的案例,我们将不胜感激。

if (StrClientID.Equals("008"))
                   objdbhims.Query += "   and (( case when t.external_org is null then d.clientid='008' end) or t.external_org in ('008','-1'))";
               else if (StrClientID.Equals("006"))
                   objdbhims.Query += " and (t.external_org<>'008' or (case when t.external_org is null then d.clientid='" + StrClientID + "' end))";
               else
                   objdbhims.Query += " and d.clientid='"+StrClientID+"'";

【问题讨论】:

  • 你可以在linq中使用三元运算符&lt;test&gt; ? &lt;valueiftrue&gt; : &lt;valueiffalse&gt;
  • @RaphaëlAlthaus case statement replace is if else but in ternary operator when I do 并且我不放 else 部分它给出了语法错误,我不想要 else 部分,怎么做/
  • 那么你可以在第二部分中添加类似m =&gt; true 的内容...
  • @RaphaëlAlthaus 谢谢你的建议作为魅力...:)

标签: c# sql linq linq-to-sql linq-to-entities


【解决方案1】:

在从 DB 获取数据之前,您可以向 IQueryable 对象添加大量 Where 子句。例如:

var data = SomeContext.MyTable.Where(x => x.SomeField == someValue);
if (someCondition) 
{
  // Something like your 1st if clause
  data = data.Where(x => (x.SomeField2 != null && x.SomeField3 == "someText") || new[] { "001", "002" }.Contains(x.SomeField2));
}

var result = data.ToList();

【讨论】:

  • 这部分怎么做?....情况下 t.external_org 为 null 然后 d.clientid='008' end) 或 t.external_org in ('008','-1') )"
  • 它检查表列值,并在此基础上添加 d.clientid ="008"
  • 这取决于你在 Linq 中 t 和 d 表之间的关系。例如,如果 d 是 Client,并且 t 具有 Client 类型的属性,那么您可以编写 t.Client.clientid == "008"。如果 t 有一个 Client(s) 列表并且您想要获取所有 t 记录,其中 t.Clients 有一些具有特定 id 的客户端,您可以这样写 - t.Clients.Any(y => y.clientid == " 008")
【解决方案2】:

在使用三元运算符与这个解决方案苦苦挣扎之后,我自己解决了这个问题,我只是将 1==1 放在 else 部分以消除错误:

string[] arr = new string[] {"008","-1"};

string ClientID = HttpContext.Current.Session["ClientID"].ToString();

&& (
                                ClientID == "008"
                             ? (t.external_org == null 
                                               ? d.clientid =="008" : 1 == 1)
                                               || (arr.Contains(t.external_org))


                                : ClientID == "006"
                             ? (t.external_org == null
                                               ? d.clientid == ClientID : 1 == 1)
                                               || (t.external_org != "008")

                        : d.clientid == ClientID
                            )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多