.net EF 6使用整数比较列表更新查询和Where子句

mmvthczy  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(174)

在EF 6.0中,我想根据WHERE过滤器更新一些记录。我从ID的整数列表中识别的记录。问题是它将ID列表视为nvarchar“61,62,63”,并且IN运算符在整数和nvarchar之间不起作用。

  1. var status = MyEnum.MyEnumValue;
  2. var idList = new List<int>(...);
  3. context.Database.ExecuteSqlInterpolated(
  4. $"UPDATE MyTable SET MyCustomStatus = {status} WHERE Id IN ({string.Join(", ", idList)})"
  5. );

字符串

错误

  1. Microsoft.Data.SqlClient.SqlException
  2. HResult=0x80131904
  3. Message=Conversion failed when converting the nvarchar value '61, 62, 63' to data type int.
  4. Source=Core Microsoft SqlClient Data Provider
  5. StackTrace:
  6. at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  7. ...


你知道什么解决办法吗?

gstyhher

gstyhher1#

您可以选择使用ExecuteSqlRaw方法,以便使用单独提供的参数的原始SQL字符串。
范例:

  1. var status = "my custom status";
  2. // Create a parameter for the list of integers
  3. var idListParameter = string.Join(",", idList.Select(id => $"@p{id}"));
  4. var parameters = idList.Select((id, index) => new SqlParameter($"@p{id}", id)).ToList();
  5. // Add a new SqlParameter for the status parameter
  6. parameters.Add(new SqlParameter("@status", status));
  7. _context.Database.ExecuteSqlRaw(
  8. $"UPDATE MyTable SET MyCustomStatus = @status WHERE Id IN ({idListParameter})",parameters.ToArray()
  9. );

字符串

展开查看全部

相关问题