ObjectiveIn this post, I will show you how to retrieve data from related entities in WCF Data Service. If you are new to this topic, please read Introduction to WCF Data service and ODATA before going through below article,Let us say, we want to fetch details from related entities Customers and Order. There are two ways to fetch data from both related entities. 1. Expand 2. LoadProperty Using LoadPropertyProgram.cs using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using ConsoleApplication1.ServiceReference1;
namespace ConsoleApplication1
{class Program
{static void Main(string[] args)
{
NorthwindEntities context = new NorthwindEntities(new Uri("http://localhost:61091/WcfDataService1.svc/"));try{foreach (Order o in context.Orders)
{
context.LoadProperty(o, "Customer");
Console.WriteLine("Customer : {0}- Order Id: {1}", o.Customer.ContactName, o.OrderID);
}
}catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
}
}
In above code So in above code load property is being used to load data from related entities. Output Using ExpandProgram.cs NorthwindEntities context = new NorthwindEntities(new Uri("http://localhost:61091/WcfDataService1.svc/"));
DataServiceQuery<Order> query =
context.Orders.Expand("Order_Details,Customer");try{foreach (Order order in query.Take(4))
{
Console.WriteLine("Customer: {0}", order.Customer.ContactName);
Console.WriteLine("Order ID: {0}", order.OrderID);foreach (Order_Detail item in order.Order_Details)
{
Console.WriteLine("\tProduct: {0} - Quantity: {1}",
item.ProductID, item.Quantity);
}
}
}catch (DataServiceQueryException ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
So in above code In above code Orders relation is expanded to Order_detail and Customer. In above code retrieving top 4th record and iterating through the records to display. Output That's all. enjoy happy coding. |