简体   繁体   中英

Linq to SQL query not returning expected results

Can anyone explain to me why these two are different functionally?

The first returns null on my sample data, and the second returns the expected result. I put the + @"" part in to avoid calling replace on a null string.

Code always returns null on my sample data:

to_follows_contact = db.CONTACTs.Where(n =>
    n.ACCOUNTID == account.ACCOUNTID
    && (
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"") 
                                                            == @"TOFOLLOW"
        ||
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"") 
                                                            == @"FOLLOWTO"
    )
).FirstOrDefault();

Code returns correct contact on my sample data:

foreach (CONTACT n in db.CONTACTs.Where(n => n.ACCOUNTID == account.ACCOUNTID))
{
    string ContactName = (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"")
                         .Replace(@" ", @"");
    if (ContactName == @"TOFOLLOW" || ContactName == @"FOLLOWTO")
        to_follows_contact = n;
}

What's happening, is that the first code sample actually solves the problem entirely in T-SQL. Unfortunately, the translation from C# to SQL isn't entirely transparent.

SQL handles null values differently* from .NET. SELECT 'Foo' + NULL + 'Bar' will return NULL . You will need to use COALESCE or something like it. In LINQ to SQL, that translates to:

(n.FIRSTNAME ?? "" + n.MIDDLENAME ?? "" + n.LASTNAME ?? "").Replace(" ", "")

If you use that, it should work fine.

If you're interested, you can use db.GetCommand(IQueryable<T>) to get the generated SQL statement. It's also available when you hover over the IQueryable variable in a piece of source code while debugging.

*: this acually depends on some database options that you can set, but this is the default behavior.

At a guess, the generated SQL will concatenate the various strings, however, if one of them is null, then you'll always get NULL returned from the concatenation, which will fail to pass your equality test.

In the code, the strings will always be empty, which will then work.

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