Search code examples
linqwcf-data-serviceslinqpad

Linq query error


I am using following Linq query:

from p in People
 where p.Name == "George Lucas"
select p.TitlesActedIn

where TitlesActedIn is a list. People and TitlesActedIn are associted

But I am getting error:

InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.PropertyExpression' to type 'System.Data.Services.Client.ResourceExpression'.

Please suggest solution.


Solution

  • A very simple way to do it:

    var query = People
        .Expand("TitlesActedIn")
        .Where(p => p.Name == "George Lucas")
        .First()
        .TitlesActedIn.Select(t => t.ShortName);              
    query.Dump();
    

    Its important to note, that this will crash if the name you pass it does not exist. (The First Operator will throw an exception. You would need to either guarantee that the name exists, or do it in two steps.


    If you want to do it in one step it comes down to this:(please note what is coming back)

    http://odata.netflix.com/catalog/People()?$filter=Name eq 'George Lucas'&$top=1&$expand=TitlesActedIn
    

    You need the expand or it will quit evaluating after the .First(), because TitlesActedIn will be empty.

    It basically translates to select the Person, include (expand) the TitlesActedIn association, then select the name (client side)

    The downside of this is that you are pulling back everything (all fields) from the Titles table. So for every title associated to the Person it is returning (Title, Year, Description, ShortName, etc).

    If you did this in two queries you could only pull back "ShortName" from the TitlesActedIn association.