简体   繁体   中英

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

A query parameter cannot be of type int64[].

Why is this?

You are passing an array of longs into a placeholder where a string is expected. 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. Then you can easily use String.Join here to convert that array to the concatenated text that you want.

I had trouble with this and I found that Linq is very particular about parameters. I had to build the SQL statement as a string and pass that string to .ExecuteCommand() for it to work. 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?

I've used the SQL profiler but it's a tad vague.

You can't do this. SQL parameters must be single values.

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. See this question for instructions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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