简体   繁体   中英

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?

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
}

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:

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM