开发者

Deferred Evaluation of strings in Linq to SQL

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开发者_JAVA百科 exited. Can anyone offer some insight into this situation?

Thanks.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜