在IN子句中-C#

时间:2019-02-07 18:46:13

标签: c#

我需要在IN中做一个ID (INT)子句

但是当我这样做时:

  strQuery = "SELECT something FROM some table \n";
  strQuery += "WHERE ID IN ({0})";

  var idParameterList = new List<string>();

  foreach (var id in lstLigID)
  {
      idParameterList.Add(id.ToString());
  }

  dbContext.Database.ExecuteSqlCommand(strQuery, string.Join(",", idParameterList));

我收到此错误:
enter image description here

2 个答案:

答案 0 :(得分:0)

选中此选项可获得更清洁的解决方案,并带有参数化查询

Dictionary<string, object> pars = new Dictionary<string, object>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < idParameterList.Count; i++)
     pars.Add($"{{{i}}}", idParameterList[i]);
sb.Append(String.Join(",", pars.Keys.ToArray()));

var finalQuery = strQuery + sb.ToString() + ");";

 dbContext.Database.ExecuteSqlCommand(finalQuery , pars.Values.ToArray()).ToList();

其中strQuery需要拥有select ... from ... where id IN (

答案 1 :(得分:-2)

我明白了

strQuery += "WHERE ligID IN (";    
strQuery += String.Join(",", lstLigID) + ");";

dbContext.Database.ExecuteSqlCommand(strQuery);
  

感谢所有试图帮助我的人