0
votes

I am new to both odata and c# and I cannot figure out how to translate URI query like the following:

http://services.odata.org/Northwind/Northwind.svc/Customers(10)/Orders?$expand=Order_Details

in c#, using the linq method syntax.

I tried this way:

var customer = context.Customers.Where( x => x.Id == 10 ).First();

foreach(var order in customer.Orders.Expand("Order_Details")){
    //stuff
}

But customer.Orders does not have the "Expand" method. How do I deal with these queries where I have to expand a navigation property connected to a specific entity?

2
Add the proper using statement: using System.Data.Services.Client;.CodeCaster
The problem is that I can actually use Expand method with Customers: var orders = context.Customers.Expand("Orders") is correct, but this results in this query: http://services.odata.org/Nortwind/Northwind.svc/Customers?$expand=OrdersAndrea Tucci

2 Answers

1
votes

First of all your code cannot compile. x => c.Id == 10 is wrong; also there is a closing paranthesis on your foreach missing. Second, you need to include Orders in your customer variable to do this.

I am using this Northwind v3 service to demonstrate this (http://services.odata.org/V3/Northwind/Northwind.svc/) as well as LinqPad (www.linqpad.net)

var customer = Customers.Expand("Orders/Order_Details")
                        .Where(cus => cus.CustomerID == "ALFKI");

foreach (var element in customer)
{
    element.Orders.Dump();
}

This results in an URL call like this one:

http://services.odata.org/V3/Northwind/Northwind.svc/Customers('ALFKI')?$expand=Orders/Order_Details

Output:

enter image description here

Larger Image

//EDIT Based on the comments below. If you do not want to go over the customer table and expand orders AND order_details, you can do it like this as well:

var orders = Orders.Expand("Order_Details")
                   .Where(o => o.CustomerID == "ALFKI").Dump();

OR

var orders = Orders.Expand(ex => ex.Order_Details)
                   .Where(o => o.CustomerID == "ALFKI").Dump();
2
votes

You will have to request for all the child properties you need as part of the OData query itself.

try following

context.Customers.Expand("Orders/Order_Details").Where(c => x => c.Id == 10 ).First();
foreach(var order in customer.Orders){
    //stuff
}