Utilizzo di associazioni nel codice di un'applicazione (EDM)

Il modello a oggetti progettato nell'argomento Implementazione delle associazioni (EDM) relativo a Entity Data Model (EDM) può essere utilizzato dalle applicazioni client. Le applicazioni EDM possono creare un'istanza dei dati, eseguire query sui dati e salvare in modo permanente i dati senza istruzioni SQL. Per ulteriori informazioni, vedere Cenni preliminari su Object Services (Entity Framework).

Il codice dell'applicazione utilizzato in questo argomento illustra come creare un'istanza di associazioni delle entità denominate Customers e Orders e spostarsi nelle associazioni tra Customers e Orders e tra Orders e OrderLines.

Creazione e inizializzazione di entità

Nel frammento di codice seguente viene illustrato come creare un'istanza di ognuno dei tre tipi: Customers, Orders e OrderLines. Viene creata un'istanza di una connessione allo spazio dei nomi OrderInfo in una riga di codice: OrderInfo orderInfo = new OrderInfo().

Poiché le entità sono classi programmabili, vengono create utilizzando il costruttore fornito quando la libreria di classi viene compilata. Aggiungere queste entità nel contesto dell'oggetto utilizzando il metodo AddToOrderInfo di OrderInfoObjectContext. Per ulteriori informazioni, vedere Aggiunta, modifica ed eliminazione di oggetti (Entity Framework).

Tramite l'esempio di codice seguente vengono creati un oggetto Customer, un oggetto Order e un oggetto OrderLine. Viene inoltre creata un'istanza delle associazioni tra Customer e Order e tra Order e OrderLine.

Dopo essere stati inizializzati nel codice seguente, gli oggetti vengono aggiunti all'archivio e le modifiche vengono salvate.

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

Spostamento tra le associazioni

Accedere agli oggetti Orders correlati a Customers e agli oggetti OrderLines correlati a Orders utilizzando le associazioni con l'oggetto NavigationProperty specificato nello schema di progettazione. Per ulteriori informazioni sulle proprietà di navigazione, vedere Elemento NavigationProperty (EntityType CSDL).

Tutte le proprietà utilizzate in questo esempio sono descritte in Implementazione delle associazioni (EDM).

Il ciclo foreach consente di recuperare l'insieme di Orders contenuto nell'oggetto Customer.OrdersNavigationProperty e ciascuno degli oggetti OrderLines contenuti in Order.OrderLinesNavigationProperty. Prima di spostarsi in queste proprietà, è necessario chiamare il metodo Load. Il metodo Load ottiene gli elementi dal database. In alternativa al metodo Load, è possibile utilizzare la proprietà Source di Orders e 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);
                        }
                    }

Connessione nella configurazione dell'applicazione

Per l'utilizzo delle entità e delle associazioni del modello a oggetti OrderInfo è necessaria una connessione al database in cui sono archiviati i dati per le applicazioni compilate in base al modello EDM (Entity Data Model). L'apertura della connessione utilizzata dal codice dell'applicazione è analoga all'apertura di una connessione SQL. Oltre alla stringa di connessione utilizzata da una connessione SQL per identificare il database e il server utilizzati da questo modello, la connessione richiede un percorso delle specifiche di mapping e degli schemi EDM. In questo esempio un file app.config contiene la stringa di connessione e il percorso dei metadati. Il contenuto di app.config è illustrato nel codice seguente:

?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>

Esempio

Il codice completo utilizzato per eseguire il segmento precedente è illustrato nell'esempio seguente. La chiamata al metodo ComputeOrder**** di supporto è identificata da un commento nell'ultimo segmento del codice. Per l'implementazione del metodo di supporto, vedere Procedura: personalizzare oggetti dati generati (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());
            }
            
        }
    }
}

Vedere anche

Concetti

Implementazione delle associazioni (EDM)
Proprietà di navigazione (EDM)