Expand and Load: Fetching Related Entities in WCF Data Service

HTML clipboard

Objective

In 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.

WCF1.gif

There are two ways to fetch data from both related entities.

  1. Expand
  1. LoadProperty

Using LoadProperty

Program.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Data.Services.Client;
using ConsoleApplication1.ServiceReference1;
namespace ConsoleApplication1
{
classProgram
    {
staticvoid Main(string[] args)
        {

NorthwindEntities context = newNorthwindEntities(newUri("http://localhost:61091/WcfDataService1.svc/"));
try
            {
foreach (Order o incontext.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

WCF2.gif

So in above code load property is being used to load data from related entities.

Output

WCF3.gif

Using Expand

Program.cs

NorthwindEntities context = newNorthwindEntities(newUri("http://localhost:61091/WcfDataService1.svc/"));
DataServiceQuery<Order> query =
context.Orders.Expand("Order_Details,Customer");

try
            {
foreach (Orderorderinquery.Take(4))
                {
Console.WriteLine("Customer: {0}", order.Customer.ContactName);
Console.WriteLine("Order ID: {0}", order.OrderID);

foreach (Order_Detail item inorder.Order_Details)
                    {
Console.WriteLine("\tProduct: {0} - Quantity: {1}",
item.ProductID, item.Quantity);
                    }
                }
            }
catch (DataServiceQueryException ex)
            {
Console.WriteLine(ex.Message);
            }

Console.Read();

Console.Read();

So in above code

WCF4.gif

In above code Orders relation is expanded to Order_detail and Customer.

WCF5.gif

In above code retrieving top 4th record and iterating through the records to display.

Output

WCF6.gif

 

Up Next
    Ebook Download
    View all
    Learn
    View all