Procedura: associare oggetti a controlli Windows Form (Entity Framework)

Entity Framework consente di associare controlli Windows Form, come ComboBox o DataGridView a un oggetto EntityCollection o a un risultato di ObjectQuery. È consigliabile non associare i controlli direttamente a un oggetto ObjectQuery. Associare invece i controlli al risultato del metodo Execute. Per ulteriori informazioni, vedere Associazione di oggetti ai controlli (Entity Framework).

L'esempio incluso in questo argomento è basato sul modello Sales di AdventureWorks. Per eseguire il codice incluso in questo esempio, è necessario avere già aggiunto il modello Sales di AdventureWorks al progetto e avere configurato il progetto per l'utilizzo di Entity Framework. A tale scopo, completare le procedure descritte in Procedura: configurare manualmente un progetto di Entity Framework e Procedura: definire manualmente i file di modello e di mapping (Entity Framework).

Esempio

L'esempio seguente deriva da un Windows Form. Quando il form viene caricato, viene restituita una classe ObjectResult di oggetti SalesOrderHeader chiamando il metodo Execute di ObjectQuery. Questo risultato è associato a una casella combinata. Quando viene selezionato un ordine, la classe EntityCollection correlata di oggetti SalesOrderDetail viene associata a un controllo DataGridView.

using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Objects;
using System.Data.Objects.DataClasses;

namespace Microsoft.Samples.Edm
{
    public partial class Main : Form
    {
        private AdventureWorksEntities context;
        private int customerId = 277;

        public Main()
        {
            // Initializes the designer-generated controls.
            InitializeComponent();
        }
        
        private void Main_Load(object sender, EventArgs e)
        {
            // Initialize the object context.
            context = new AdventureWorksEntities();
            try
            {
                // Create a query for orders that includes line items.
                ObjectQuery<SalesOrderHeader> orderQuery = context.SalesOrderHeaders
                    .Where("it.CustomerID = @customerId", 
                    new ObjectParameter("customerId", customerId))
                    .Include("SalesOrderDetails");

                // Display the PO number in the combo box.
                this.ordersListBox.DisplayMember = "PurchaseOrderNumber";

                // Bind the combo box to the ObjectResult of SalesOrderHeader 
                // that is returned when the query is executed.
                this.ordersListBox.DataSource = orderQuery.Execute(MergeOption.AppendOnly);
            }
            catch (EntitySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ordersListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the currently selected SalesOrderHeader object.
            SalesOrderHeader order = (SalesOrderHeader)this.ordersListBox.SelectedItem;

            // Bind the items for this order to the DataGridView.
            lineItemsDataGrid.DataSource = order.SalesOrderDetails;
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            // Get the current order.    
            SalesOrderHeader order = (SalesOrderHeader)ordersListBox.SelectedItem;

            try
            {
                // Save changes in the object context.
                context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
            }
            catch (OptimisticConcurrencyException)
            {
                // Resolve the concurrently conflict by refreshing the 
                // object context before saving changes. 
                context.Refresh(RefreshMode.ClientWins, order.SalesOrderDetails);

                // Resave changes in the object context.
                context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.InnerException.Message, "An error has occured");
            }
            finally
            {
                //  Refresh the latest data from the database.
                context.Refresh(RefreshMode.StoreWins, order);
                this.Refresh();
            }
        }
    }
}

Vedere anche

Attività

Procedura: associare oggetti a controlli Windows Presentation Foundation (Entity Framework)
Procedura: aggiungere un oggetto come origine dati progetto (Entity Framework)

Concetti

Associazione di oggetti ai controlli (Entity Framework)