views:

64

answers:

1

Hi!
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?

A: 

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(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.

Will
Thank you for your help. I think TraceSql should be TraceSql<T>.
Daniel