Share via


Application Code Using Associations (EDM)

The object model designed in the Entity Data Model (EDM) topic Implementing Associations (EDM) can be used by client applications. EDM applications can instantiate, query, and persist data without SQL statements. For more information, see Object Services Overview (Entity Framework).

The application code demonstrated in this topic shows how to instantiate associations of the entities named Customers and Orders and navigate the associations between Customers and Orders and between Orders and OrderLines.

Creating and Initializing Entities

The following code snippet shows how to create one instance of each of three types: Customers, Orders, and OrderLines. A connection to OrderInfo namespace is instantiated in one line of code: OrderInfo orderInfo = new OrderInfo().

Because the entities are programmable classes, they are created by using the constructor provided when the class library is built. Add these entities to the object context by using the AddToOrderInfo method of the OrderInfo ObjectContext. For more information, see Adding, Modifying, and Deleting Objects (Entity Framework).

The following code segment creates a Customer, an Order, and an OrderLine. The code also instantiates associations between the Customer and the Order, and between the Order and the OrderLine.

After the objects have been initialized in the following code, they are added to storage and the changes are saved.

                    Dim i As Integer = 0
                    Dim newCustomer As Customers = _
                    New Customers()
                    newCustomer.CustomerId = _
                                    Guid.NewGuid()
                    newCustomer.Name = "Customer-" + _
                                    i.ToString()
                    newCustomer.Address = "Address-" + _
                                    i.ToString()
                    newCustomer.City = "Redmond"
                    newCustomer.Phone = "123 456-7890"
                    newCustomer.ZipCode = 98054

                    Dim newOrder As New Orders()
                    newOrder.OrderId = i.ToString()
                    newOrder.Customers = newCustomer
                    newOrder.ShippingAddress = _
                                "Address-" + i.ToString()
                    newOrder.Tax = 0
                    newOrder.TotalAmount = 0

                    Dim newOrderLines As OrderLines = New OrderLines()
                    newOrderLines.OrderLineId = Guid.NewGuid()
                    newOrderLines.ProductName = "Product-" + _
                    i.ToString()
                    newOrderLines.Quantity = 2
                    newOrderLines.UnitPrice = 67.71
                    newOrderLines.ExtendedPrice = _
                        newOrderLines.Quantity * _
                        newOrderLines.UnitPrice

                    newOrder.OrderLines.Add(newOrderLines)

                    orderInfo.AddToCustomers(newCustomer)
                    orderInfo.AddToOrders(newOrder)

                    orderInfo.SaveChanges()
                        int i = 0;
                        Customers newCustomer = new Customers();
                        newCustomer.CustomerId = Guid.NewGuid(); 
                        newCustomer.Name = "Customer-" + i.ToString();
                        newCustomer.Address = "Address" + i.ToString(); 
                        newCustomer.City = "Redmond"; 
                        newCustomer.Phone = "123 456-7890";
                        newCustomer.ZipCode = 98054;

                        Orders newOrder = new Orders();
                        newOrder.OrderId = i.ToString();
                        newOrder.Customers = newCustomer;
                        newOrder.ShippingAddress = "Address-" + 
                                                        i.ToString();
                        newOrder.Tax = 0;
                        newOrder.TotalAmount = 0;

                        OrderLines newOrderLines = new OrderLines();
                        newOrderLines.OrderLineId = Guid.NewGuid(); 
                        newOrderLines.ProductName = "Product-" +
                            i.ToString(); 
                        newOrderLines.Quantity = 2; 
                        newOrderLines.UnitPrice = (decimal)67.70; 
                        newOrderLines.ExtendedPrice = 
                            newOrderLines.Quantity * 
                            newOrderLines.UnitPrice;

                        newOrder.OrderLines.Add(newOrderLines);

                        orderInfo.AddToCustomers(newCustomer);
                        orderInfo.AddToOrders(newOrder);

                        orderInfo.SaveChanges();

Access the Orders related to Customers and the OrderLines related to Orders by using associations with the NavigationProperty specified in the design schema. For more information about navigation properties, see NavigationProperty Element (EntityType CSDL).

All of the properties used in this example are described in Implementing Associations (EDM).

The following foreach loop retrieves the collection of Orders that is contained in the Customer.Orders NavigationProperty and each of the OrderLines that is contained in the Order.OrderLines the NavigationProperty. The Load method must be called before navigating these properties. The Load method gets the items from the database. (An alternative to the Load method is to use the Source property of Orders and OrderLines.)

               For Each customer In orderInfo.Customers
                    Console.WriteLine("Customer: " + customer.Name)

                    ' If customer has orders, load orders.
                    customer.Orders.Load()
                    For Each order In orderInfo.Orders
                        Console.WriteLine(vbTab + "Order#: " _
                                          + order.OrderId)

                        ' Load orderlines
                        order.OrderLines.Load()
                        For Each orderline In order.OrderLines
                            Console.WriteLine(vbTab + vbTab + _
                                              orderline.ProductName)
                     Next
                 Next
                    foreach (Customers customer in orderInfo.Customers)
                    {
                        Console.WriteLine("Customer: " + 
                                              customer.Name);

                        //If customer has orders, load orders.
                        customer.Orders.Load();
                        foreach (Orders order in customer.Orders)
                        {
                            Console.WriteLine("\t" + order.OrderId);

                            // Load OrderLines.
                            order.OrderLines.Load();
                            foreach (OrderLines orderLine in 
                                     order.OrderLines)
                                Console.WriteLine(
                                 "\t\t" + orderLine.ProductName);
                        }
                    }

Connection in App Config

Using the entities and associations of the OrderInfo object model requires a connection the database that stores data for applications built on the Entity Data Model (EDM). Opening the connection used by application code resembles opening a SQL connection. In addition to the connection string that is used by a SQL connection to identify the database and server that is used by this model, the connection requires a path to the EDM schemas and mapping specifications. In this example, an app.config file contains the connection string and the location of the metadata. The contents of the app.config are shown in the following code:

?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="OrderInfo" 
                 connectionString='Metadata=.;
                 Provider=System.Data.SqlClient;
                 Provider Connection String="server=serverName;
                 database=OrderInfo;Integrated Security=true;
                 Connection Timeout=5;multipleactiveresultsets=true"'
                 providerName="System.Data.EntityClient"/>
    </connectionStrings>
</configuration>

Example

The complete code used to execute the previous segment is shown in the following example. The call to the helper method ComputeOrder is identified by a comment in the last segment of the code. For the implementation of the helper method, see How to: Customize Generated Data Objects (Entity Framework).

Imports OrderInfoModel
Module Module1

    Sub Main()
        Try
            Using orderInfo As OrderInfo = New OrderInfo()
                For Each customer In orderInfo.Customers
                    Console.WriteLine("Customer: " + customer.Name)

                    ' If customer has orders, load orders.
                    customer.Orders.Load()
                    For Each order In orderInfo.Orders
                        Console.WriteLine(vbTab + "Order#: " _
                                          + order.OrderId)

                        ' Load orderlines
                        order.OrderLines.Load()
                        For Each orderline In order.OrderLines
                            Console.WriteLine(vbTab + vbTab + _
                                              orderline.ProductName)
                        Next

                        For Each order2 In orderInfo.Orders
                            Console.WriteLine("Order#: " + _
                                               order2.OrderId)

                            ' Display OrderLines products and quantities.
                            order2.OrderLines.Load()
                            For Each orderline2 In order2.OrderLines
                                Console.WriteLine(vbTab + "{0} " + _
                                              "UnitPrice: ${1} " + _
                                              "Quantity: {2}", _
                                              orderline2.ProductName, _
                                              orderline2.UnitPrice, _
                                              orderline2.Quantity)

                                ' Open the commented code in this
                                ' section to use the ComputeOrder
                                ' helper method defined in the topic
                                ' Helper Methods (EDM).
                                'Console.WriteLine(vbTab + vbTab + _
                                'vbTab + "Total Order # {0}: " + _
                                '"${1} Including ${2} tax", _
                                'order2.OrderId, _
                                'Decimal.Round( _
                                'order2.ComputeOrder(), _
                                '2), _
                                'order2.Tax)

                            Next
                        Next
                    Next
                Next

                ' Set to True to add entities.
                If False Then
                    Dim i As Integer = 0
                    Dim newCustomer As Customers = _
                    New Customers()
                    newCustomer.CustomerId = _
                                    Guid.NewGuid()
                    newCustomer.Name = "Customer-" + _
                                    i.ToString()
                    newCustomer.Address = "Address-" + _
                                    i.ToString()
                    newCustomer.City = "Redmond"
                    newCustomer.Phone = "123 456-7890"
                    newCustomer.ZipCode = 98054

                    Dim newOrder As New Orders()
                    newOrder.OrderId = i.ToString()
                    newOrder.Customers = newCustomer
                    newOrder.ShippingAddress = _
                                "Address-" + i.ToString()
                    newOrder.Tax = 0
                    newOrder.TotalAmount = 0

                    Dim newOrderLines As OrderLines = New OrderLines()
                    newOrderLines.OrderLineId = Guid.NewGuid()
                    newOrderLines.ProductName = "Product-" + _
                    i.ToString()
                    newOrderLines.Quantity = 2
                    newOrderLines.UnitPrice = 67.71
                    newOrderLines.ExtendedPrice = _
                        newOrderLines.Quantity * _
                        newOrderLines.UnitPrice

                    newOrder.OrderLines.Add(newOrderLines)

                    orderInfo.AddToCustomers(newCustomer)
                    orderInfo.AddToOrders(newOrder)

                    orderInfo.SaveChanges()

                End If

            End Using

        Catch ex As Exception
            Console.WriteLine(ex.Message.ToString() + "\n" + _
                              ex.InnerException.ToString())
        End Try

    End Sub

End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OrderInfoModel;

namespace Associations_CS
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (OrderInfo  orderInfo = new OrderInfo())
                {
                    foreach (Customers customer in orderInfo.Customers)
                    {
                        Console.WriteLine("Customer: " + 
                                              customer.Name);

                        //If customer has orders, load orders.
                        customer.Orders.Load();
                        foreach (Orders order in customer.Orders)
                        {
                            Console.WriteLine("\t" + order.OrderId);

                            // Load OrderLines.
                            order.OrderLines.Load();
                            foreach (OrderLines orderLine in 
                                     order.OrderLines)
                                Console.WriteLine(
                                 "\t\t" + orderLine.ProductName);
                        }
                    }

                    foreach (Orders order in orderInfo.Orders)
                    {
                        Console.WriteLine("Order: " + order.OrderId);

                        // Display OrderLines products and quantities.
                        order.OrderLines.Load();
                        foreach (OrderLines orderLine in 
                                 order.OrderLines)
                            Console.WriteLine(
                                "\t{0}  UnitPrice: ${1} Quantity: {2}", 
                                orderLine.ProductName,
                                orderLine.UnitPrice,
                                orderLine.Quantity );

                        // Open the commented code in this section to
                        // use the ComputeOrder helper method defined
                        // in the topic Helper Methods (EDM).
                      /*Console.WriteLine("\t\t\tTotal Order #{0}: " +
                                     "${1} Including ${2} tax", 
                                     order.OrderId,
                                     Decimal.Round(
                                     order.ComputeOrder(), 2),
                                     order.Tax); */

                    }

                    if(false)  // Set to true to add entities.
                    {
                        int i = 0;
                        Customers newCustomer = new Customers();
                        newCustomer.CustomerId = Guid.NewGuid(); 
                        newCustomer.Name = "Customer-" + i.ToString();
                        newCustomer.Address = "Address" + i.ToString(); 
                        newCustomer.City = "Redmond"; 
                        newCustomer.Phone = "123 456-7890";
                        newCustomer.ZipCode = 98054;

                        Orders newOrder = new Orders();
                        newOrder.OrderId = i.ToString();
                        newOrder.Customers = newCustomer;
                        newOrder.ShippingAddress = "Address-" + 
                                                        i.ToString();
                        newOrder.Tax = 0;
                        newOrder.TotalAmount = 0;

                        OrderLines newOrderLines = new OrderLines();
                        newOrderLines.OrderLineId = Guid.NewGuid(); 
                        newOrderLines.ProductName = "Product-" +
                            i.ToString(); 
                        newOrderLines.Quantity = 2; 
                        newOrderLines.UnitPrice = (decimal)67.70; 
                        newOrderLines.ExtendedPrice = 
                            newOrderLines.Quantity * 
                            newOrderLines.UnitPrice;

                        newOrder.OrderLines.Add(newOrderLines);

                        orderInfo.AddToCustomers(newCustomer);
                        orderInfo.AddToOrders(newOrder);

                        orderInfo.SaveChanges();

                        
                    }
                }
            }

            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            
        }
    }
}

See Also

Concepts

Implementing Associations (EDM)
Navigation Properties (EDM)