简体   繁体   English

带有'IN'语句的LINQ-To-SQL ExecuteCommand

[英]LINQ-To-SQL ExecuteCommand with 'IN' statement

I have the following code: 我有以下代码:

long[] conIds = GetIDs();
dc.ExecuteCommand("UPDATE Deliveries SET Invoiced = NULL WHERE ID IN {0}",conIds);

I'd expect that to work, but the executecommand statement throws an exception stating that 我希望它能正常工作,但是executecommand语句抛出一个异常,指出

A query parameter cannot be of type int64[]. 查询参数不能为int64 []类型。

Why is this? 为什么是这样?

You are passing an array of longs into a placeholder where a string is expected. 您正在将一个long类型数组传递到一个预期包含字符串的占位符。 You need to convert the array into a concatenated string with comma delimiters. 您需要将数组转换为带有逗号分隔符的串联字符串。 Then, pass that into the command text. 然后,将其传递到命令文本中。

Depending on where else you are using the GetIDs method, you could simplify your code by having that method return an array of strings. 根据您在其他地方使用GetIDs方法的不同,可以通过使该方法返回字符串数组来简化代码。 Then you can easily use String.Join here to convert that array to the concatenated text that you want. 然后,您可以轻松地使用String.Join ,将数组转换为所需的串联文本。

I had trouble with this and I found that Linq is very particular about parameters. 我对此感到麻烦,并且发现Linq在参数方面非常讲究。 I had to build the SQL statement as a string and pass that string to .ExecuteCommand() for it to work. 我必须将SQL语句构建为字符串,然后将该字符串传递给.ExecuteCommand()才能起作用。 There was no error, just no results. 没有错误,只有结果。 Confusing. 混乱。

That said has anyone seen a good solid method of viewing what Linq is passing to Sql Server? 那就是说,有没有人看到查看Linq传递给Sql Server的好方法?

I've used the SQL profiler but it's a tad vague. 我使用过SQL事件探查器,但是有点模糊。

You can't do this. 你做不到 SQL parameters must be single values. SQL参数必须是单个值。

You can make this work by converting your array to a list of comma separated values. 您可以通过将数组转换为用逗号分隔的值列表来完成这项工作。

See here for an example. 请参阅此处的示例。

command.CommandText = command.CommandText.Replace(
  "@conIDs", 
  string.Join(conIDs.Select(b => b.ToString()), ",")
);

In general, it's better to serialize your SQL and use a table valued parameter for this sort of thing. 通常,最好对SQL进行序列化,并使用表值参数进行此类操作。 See this question for instructions. 有关说明,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM