Search code examples
entity-frameworkwcf-ria-servicesvisual-studio-lightswitch

Why does this query always return ALL records?


I'm using WCF RIA in a Lightswitch project to create some query results. This query brings back all results regardless. I cannot make it filter the records based on the parameter passed (string Town).

public IQueryable<Enquiries> TestQuery(string Town)
        {
            List<Enquiries> riaenqs = new List<Enquiries>();
            var enqs = this.Context.ClientEnquiries
                .Include("Client")
                .Include("Client.Town")
                .OrderBy(enq => enq.Id);

            if (Town != null)
            {
                enqs.Where(enq => enq.Client.Town.TownName == Town);
            }

            foreach (ClientEnquiry item in enqs.ToList())
            {
                Enquiries enq = new Enquiries();
                enq.Id = item.Id;
                enq.ClientName = item.Client.FirstName + " " + item.Client.Surname;
                enq.Town = item.Client.Town != null ? item.Client.Town.TownName : null;

                riaenqs.Add(enq);
            }

            return riaenqs.AsQueryable();
        }

During debugging I can see that the Town is correctly populated and I can see that the query is built accordingly if Town is not null. However, when I hit the foreach statement where the linq to ef query is executed I always get all the results. I just cannot figure out where I'm slipping up.


Solution

  • The LINQ methods like the Where do not modify the collection/expression but always returning a new one.

    So you need to reassign the result of the Where to your original variable enqs:

    if (Town != null)
    {
        enqs = enqs.Where(enq => enq.Client.Town.TownName == Town);
    }