简体   繁体   中英

Can anybody tell me why this linq query won't work?

Sorry if I'm missing something really obvious, I've been coding for a lot of hours in a row and my brain is crawling to a halt. I have the following statement:

var hcn = "";
var forename = "";
var surname = "";

foreach (var casenoteResult in casenoteResults)
{
    personResults.AddRange(_ctx.People.Where
        (x => x.PAS_INT_NO == casenoteResult.PAS_INT_NO 
        && x.CSA_NO.Contains(hcn) 
        && x.FORENAMES.ToLower().Contains(forename.ToLower()) 
        && x.SURNAME.ToLower().Contains(surname.ToLower()))
        .ToList());
}

And I get no result. The only thing I'm really looking for is the casenote. Yet if I comment out each of the '&&'s, so I'm left with this:

foreach (var casenoteResult in casenoteResults)
{
    personResults.AddRange(_ctx.People.Where
        (x => x.PAS_INT_NO == casenoteResult.PAS_INT_NO)
        .ToList());
}

I get 1 result, which is what I'm expected.

Can anyone help me? Why does the first statement not return this 1 result? Could it be that some of the fields that I'm comparing the empty strings to are null? The one record that gets found doesn't have any nulls in it. I'm lost here. Please help my poor battered brain!

If I were you, I would re-write this code like below. It's safer to build the queryable in parts to make sure you have a good handle on which values you are actually passing in to the query. The reason why you are not getting any rows is probably because the query values going in to the query is not what you think they are or your database doesn't treat empty string as a wildcard. (Because based on what you posted, you are checking if a string contains an empty string which is always true in C# but may not be true for your database provider).

var queryable = _ctx.People.Where(w => caseNoteResults.Select(s => s.PAS_INT_NO).Contains(w.PAS_INT_NO));

queryable = string.IsNullOrEmpty(hcn) ? queryable : queryable.Where(w => w.CSA_NO.Contains(hcn, StringComparison.InvariantCulture));

queryable = string.IsNullOrEmpty(forename) ? queryable : queryable.Where(w => w.FORENAMES.Contains(forename, StringComparison.InvariantCultureIgnoreCase));

queryable = string.IsNullOrEmpty(surname) ? queryable : queryable.Where(w => w.SURNAME.Contains(surname, StringComparison.InvariantCultureIgnoreCase));

personResults.AddRange(queryable.ToList());

The idea is, if your hcn , forename and surname are empty, no point in checking them.

Also, make sure that you handle nulls safely if each of these fields are nullable.

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