Why are my bound parameters all identical (using Linq)?
Posted
by Scott Stafford
on Stack Overflow
See other posts from Stack Overflow
or by Scott Stafford
Published on 2010-05-13T13:18:38Z
Indexed on
2010/05/13
13:24 UTC
Read the original article
Hit count: 176
When I run this snippet of code:
string[] words = new string[] { "foo", "bar" };
var results = from row in Assets select row;
foreach (string word in words)
{
results = results.Where(row => row.Name.Contains(word));
}
I get this SQL:
-- Region Parameters
DECLARE @p0 VarChar(5) = '%bar%'
DECLARE @p1 VarChar(5) = '%bar%'
-- EndRegion
SELECT ... FROM [Assets] AS [t0]
WHERE ([t0].[Name] LIKE @p0) AND ([t0].[Name] LIKE @p1)
Note that @p0
and @p1
are both bar
, when I wanted them to be foo
and bar
.
I guess Linq is somehow binding a reference to the variable word
rather than a reference to the string currently referenced by word
? What is the best way to avoid this problem?
(Also, if you have any suggestions for a better title for this question, please put it in the comments.)
Note that I tried this with regular Linq also, with the same results (you can paste this right into Linqpad):
string[] words = new string[] { "f", "a" };
string[] dictionary = new string[] { "foo", "bar", "jack", "splat" };
var results = from row in dictionary select row;
foreach (string word in words)
{
results = results.Where(row => row.Contains(word));
}
results.Dump();
Dumps:
bar
jack
splat
© Stack Overflow or respective owner