Share via


HOW TO:將物件繫結到 Windows Form 控制項 (Entity Framework)

Entity Framework 可以讓您將 Windows Form 控制項 (例如 ComboBoxDataGridView) 繫結到 EntityCollectionObjectQuery 結果。 建議您不要將控制項直接繫結到 ObjectQuery, 最好是將它們繫結到 Execute 方法的結果。 如需詳細資訊,請參閱將物件與控制項繫結 (Entity Framework)

本主題的範例是根據 Adventure Works Sales Model。 若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。 若要這樣做,請完成 HOW TO:手動設定 Entity Framework 專案HOW TO:手動定義模型和對應檔 (Entity Framework) 中的程序。

範例

下列範例是來自 Windows Form。 表單載入時,SalesOrderHeader 物件的 ObjectResult 會藉由呼叫 ObjectQueryExecute 方法傳回。 這個結果會繫結到下拉式方塊。 選取某個訂單時,SalesOrderDetail 物件的相關 EntityCollection 便會繫結到 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();
            }
        }
    }
}

另請參閱

工作

HOW TO:將物件繫結到 Windows Presentation Foundation 控制項 (Entity Framework)
HOW TO:將物件加入做為專案資料來源 (Entity Framework)

概念

將物件與控制項繫結 (Entity Framework)