Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq & String.ToLower() strange behavior


I have a query on the server side that returns a list of distinct cities from a zipcode table.
I'm using WCF RIA Service.
The following query successfully returns 228 cities when provincename == ""

    public IQueryable<CityPM> GetCities(string provinceName)
    {
        return this.ObjectContext.ZipCodes.Where(z => z.Province.Contains(provinceName))
                                          .GroupBy(z => z.City)
                                          .Select(g => g.FirstOrDefault())
                                          .Select(zc => new CityPM() { ID = zc.ID, Name = zc.City });
    }

but if I use ToLower() method as below, the query returns 0 cities when provincename == "".

    public IQueryable<CityPM> GetCities(string provinceName)
    {
        return this.ObjectContext.ZipCodes.Where(z => z.Province.ToLower().Contains(provinceName.ToLower()))
                                          .GroupBy(z => z.City)
                                          .Select(g => g.FirstOrDefault())
                                          .Select(zc => new CityPM() { ID = zc.ID, Name = zc.City });
    }

Why isn't the query returning anything?

like image 663
Yeonho Avatar asked Dec 12 '22 18:12

Yeonho


1 Answers

Try checking the SQL generated, either by using DB management tools, or calling .ToTraceString() at the end of the query expression.

Reference: http://blog.aggregatedintelligence.com/2010/06/viewing-entity-framework-generated-sql.html

We use ToTraceString at work using an extension:

public static IQueryable<T> TraceSql<T>(this IQueryable<T> query)
{
    var sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();

    // do whatever logging of sql you want here, eg (for web)
    // (view by visiting trace.axd within your site)
    HttpContext.Current.Trace.Write("sql", sql);

    return query;
}

It can then be used as follows:

public IQueryable<CityPM> GetCities(string provinceName)
{
    return this.ObjectContext.ZipCodes.Where(z => z.Province.ToLower().Contains(provinceName.ToLower()))
                                      .GroupBy(z => z.City)
                                      .Select(g => g.FirstOrDefault())
                                      .Select(zc => new CityPM() { ID = zc.ID, Name = zc.City })
                                      .TraceSql();
}

Please forgive me for any typos, this is from memory. Hopefully it will help you understand your problem.

like image 93
Will Avatar answered Dec 23 '22 06:12

Will