Search code examples
linqwcf-data-servicesodata

WCF service operations to return an object graph


I have a WCF service Operation, I'd like it to return an object graph rather than a simple list of objects. Is there some magic LinQ to do this?

Thanks

A bit more info is possibly needed:

I have a couple of entities:

StockableItem
+ Id
+ Code

Stock
+ Id
+ Location
+ Qty

StockableItem->Stock is a 1..* relationship.

and I am failing with this linq:

from si in svc.StockableItems.Include("Stock")
join s in svc.Stock on si.Id equals s.Id
where s.Location == 1 select si

and several variations.

I'm hoping the service operation will be able to return something like this:

StockableItem - ID=213, Code=xxx
StockableItem - ID=214, Code=xxx2
    + Stock - ID=214, Location=1, Qty=3
StockableItem - ID=215, Code=xxx3
StockableItem - ID=216, Code=xxx4
    + Stock - ID=216, Location=1, Qty=6

i.e. To return all StockableItems along with the Stock entries for the given location. It's pretty much just a left outer join:

Select * from StockableItems si
Left outer join Stock s ON si.Id = s.Id and s.Location = @Location

but turned into an object graph.


Solution

  • It's not entirely clear; sounds like you'd ideally want an OData solution. You can't return an object graph from a WCF Data services service operation called from an OData query. You can get a flat list of objects but then need to use $expand to get the object graph. In your case $expand won't work, it'll return all the stock instances for whichever StockItems pass the filter.

    I think your best bet would be to create a view in your DB (I assume you have a table of locations?)

        SELECT       si.Id, Locations.Location 
        FROM         StockableItem AS si  
        CROSS JOIN   Locations
    

    In your entity model, add this view as an entity (called XXX say) and set up navigation properties between it and your StockableItem and Stock entities.

    Now you can run OData queries like

    .../XXX?$expand=StockableItem,Stock&$filter=isof(Stock,'YourModelName.Stock') and Location eq 1
    

    It's not the exact object graph you were after but, unless you want to start adding links client side, it's the best you're going to get.