Nick L
Nick L

Reputation: 145

Using Linq to filter parents by their children

Having some problems with my Silverlight app (with RIA services) filtering my results. The idea is on the client I set up the EntityQuery and its filters and call load. However this isn't working for me.

Heres my code.

public void FireQuery(string filterValue)
{
    EntityQuery<Parent> query = m_ParentDomainContext.GetParentQuery();
    query = query.Where(p => p.Children.Any(c => c.Name.Contains(filterValue)));
    m_ParentDomainContext.Load(query, Query_Completed, null);
}

Compiles just fine, however, runtime I get "Query operator 'Any' is not supported." Exception. Does anyone know of a good way to filter like this? Again, I'm looking for a way to set this up on the client.

EDIT: I should note, I've tried a few other queries as well, with similar results:

query = query.Where(p => p.Children.Where(c => c.Name.Contains(filterValue)).Count() != 0);

query = query.Where(p => p.Children.Where(c => c.Name.Contains(filterValue)).FirstOrDefault != null);

query = query.Where(p => p.Children.Where(c => c.Name.Contains(filterValue)).Any());

Query Operator 'Count/FirstOrDefault/Any' is not supported. I'm clearly missing something here...

Upvotes: 1

Views: 723

Answers (1)

AbdouMoumen
AbdouMoumen

Reputation: 3854

As I tried to play around a little with this, I figured out that methods like First, Any and Count can't be used with LINQ to Entities (and, I believe, even NHibernate) over WCF RIA Services because they're not defined on the IQueryable itself, but, instread, are extention methods defined in the System.Linqnamespace. That is precisely why this shows as a run-time exception and not a compile-time error. The only extension methods that can be used here are those found in System.ServiceModel.DomainServices.Client (such as Where, Skip, Take, OrderBy, etc.).

This has to do with the "EntityQuery" objects, because those need to be composed and sent back to the server, whereas for the collections (such as m_ParentDomainContext.Parents in your case), you can use the System.Linq extension methods freely.

In order to implement this functionality, I suggest, as Thomas Levesque said, to expose it from the server in order to only get the data you want, or, alternatively, you can compose a query using the available constructs (the ones in System.ServiceModel.DomainServices.Client) and then apply the other filters on the resulting data (where you can use extension methods from the System.Linq namespace).

PS: I tried this with both classic Entity Framework and Entity Framework CodeFirst, and had the same results.

I hope this helps

Upvotes: 1

Related Questions