Expand and Load: Fetching related entities in WCF Data Service


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.


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

1. Expand

2. LoadProperty

Using LoadProperty


  NorthwindEntities context = new NorthwindEntities(new Uri("http://localhost:61091/WcfDataService1.svc/"));
                    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)

In above code clip_image003 So in above code load property is being used to load data from related entities. Output clip_image005 Using Expand Program.cs

 DataServiceQuery<Order> query =
                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)

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.



2 responses to “Expand and Load: Fetching related entities in WCF Data Service”

  1. How would that work with a many to many entity sets.

    AssetEntity : AssetId,Name
    AssetTagJoin : AssetId,TagId
    TagEntity: TagId,TagName

    I tried cxt.Asset.Expand(“AssetTagJoin”) – works
    cxt.Asset.Expand(“AssetTagJoin”).Expand(“TagEntity”) — does not work.
    cxt.Asset.Expand(“AssetTagJoin,TagEntity”) — does not work.

    thank you.
    Mike Apken

    I’m using WCF DataServices, EF

  2. Dhananjay Kumar

    Hi ,

    You can use the query as
    DataServiceQuery query = context.AssetEntity.Expand(“AssetTagJoin,Tagentity”);

    I hope above should work

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com