Andrea Tucci
Andrea Tucci

Reputation: 187

oData query in c#

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?

Upvotes: 0

Views: 3029

Answers (2)

Marco
Marco

Reputation: 23917

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();

Upvotes: 2

Antony Francis
Antony Francis

Reputation: 304

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
}

Upvotes: 2

Related Questions