linq中where子句中的sql case语句

时间:2013-11-27 07:35:45

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

这是我的字符串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+"'";

2 个答案:

答案 0 :(得分:0)

在从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();

答案 1 :(得分:-1)

我通过使用三元运算符在这个解决方案中苦苦挣扎后自己解决了这个问题,我只是在else部分放了1 == 1来摆脱错误:

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
                            )