Question

I seem to be having a problem when using Linq to Sql in which the Where method adds a string reference to the criteria list. When the reference is changed, it produces erroneous results. For example, the code snippet below when used with the input text 'John Smith' returns all records whose name contains 'Smith'

var qry = from c in ctx.Customers select c;

if (!string.IsNullOrEmpty(Name.Text))
{
    foreach(string s in Name.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
        qry = qry.Where(c => c.Name.Contains(s));
}

ResultSet.DataSource = qry;
ResultSet.DataBind();

This snippet actually executes the following Sql:

SELECT (fields)
FROM [dbo].[Customers] AS [t0]
WHERE ([t0].[Name] LIKE @p0) AND ([t0].[Name] LIKE @p1)

@p0='%smith%',@p1='%smith%'

Note that both parameters are evaluated to "smith" which happens to be the last value of s after the foreach loop has exited. Can anyone offer some insight into this situation?

Thanks.

Was it helpful?

Solution

var qry = from c in ctx.Customers select c;

if (!string.IsNullOrEmpty(Name.Text))
{
    foreach(string str in Name.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
    {
        var s = str;
        qry = qry.Where(c => c.Name.Contains(s));
    }
}

ResultSet.DataSource = qry;
ResultSet.DataBind();

for why, read this http://blogs.msdn.com/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top