방법: Windows Form 컨트롤에 개체 바인딩(Entity Framework)
개체 서비스를 사용하면 ComboBox 또는 DataGridView와 같은 Windows Form 컨트롤을 EntityCollection 또는 ObjectQuery 결과에 바인딩할 수 있습니다. 컨트롤을 ObjectQuery에 직접 바인딩하지 않는 것이 좋습니다. 대신, 컨트롤을 Execute 메서드의 결과에 바인딩하십시오. 자세한 내용은 컨트롤에 개체 바인딩(Entity Framework)을 참조하십시오.
이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 예제의 코드를 실행하려면 프로젝트에 AdventureWorks Sales 모델을 추가하고 Entity Framework를 사용하도록 프로젝트를 구성해야 합니다. 이렇게 하려면 방법: Entity Framework 프로젝트 수동 구성 및 방법: 엔터티 데이터 모델 수동 정의(Entity Framework)의 절차를 수행합니다.
예제
다음 예제는 Windows Form에서 가져온 것입니다. 폼이 로드되면 ObjectQuery의 Execute 메서드를 호출하는 방법으로 SalesOrderHeader 개체의 ObjectResult가 반환됩니다. 이 결과는 콤보 상자에 바인딩됩니다. 주문을 선택하면 SalesOrderDetail 개체의 관련 EntityCollection이 DataGridView 컨트롤에 바인딩됩니다.
Imports System
Imports System.Collections.Generic
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Imports AdventureWorksModel
Public Class Main
Public Sub New()
' Initializes the designer-generated controls.
InitializeComponent()
End Sub
Private context As AdventureWorksEntities
Private customerId As Integer = 277
Private Sub Main_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
' Initialize the object context.
context = New AdventureWorksEntities()
Try
' Create a query for orders that includes line items.
Dim orderQuery As ObjectQuery(Of SalesOrderHeader) = _
context.SalesOrderHeader _
.Where("it.CustomerID = @customerId", _
New ObjectParameter("customerId", customerId)) _
.Include("SalesOrderDetail")
' Bind the combo box to the ObjectResult of SalesOrderHeader
' that is returned when the query is executed.
Me.ordersListBox.DataSource = orderQuery.Execute(MergeOption.AppendOnly)
' Display the PO number in the combo box.
Me.ordersListBox.DisplayMember = "PurchaseOrderNumber"
Catch ex As EntitySqlException
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ordersListBox_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles ordersListBox.SelectedIndexChanged
' Get the currently selected SalesOrderHeader object.
Dim order As SalesOrderHeader = CType(Me.ordersListBox.SelectedItem, _
SalesOrderHeader)
' Bind the items for this order to the DataGridView.
lineItemsDataGrid.DataSource = order.SalesOrderDetail
End Sub
Private Sub saveButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles saveButton.Click
' Get the current order.
Dim order As SalesOrderHeader = CType(ordersListBox.SelectedItem, _
SalesOrderHeader)
Try
' Save changes in the object context.
context.SaveChanges(True)
Catch ex As OptimisticConcurrencyException
' Resolve the concurrently conflict by refreshing the
' object context before saving changes.
context.Refresh(RefreshMode.ClientWins, order.SalesOrderDetail)
' Resave changes in the object context.
context.SaveChanges(True)
Catch ex As Exception
MessageBox.Show(ex.InnerException.Message, "An error has occured")
Finally
' Refresh the latest data from the database.
context.Refresh(RefreshMode.StoreWins, order)
Me.Refresh()
End Try
End Sub
End Class
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;
using AdventureWorksModel;
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.SalesOrderHeader
.Where("it.CustomerID = @customerId",
new ObjectParameter("customerId", customerId))
.Include("SalesOrderDetail");
// Bind the combo box to the ObjectResult of SalesOrderHeader
// that is returned when the query is executed.
this.ordersListBox.DataSource = orderQuery.Execute(MergeOption.AppendOnly);
// Display the PO number in the combo box.
this.ordersListBox.DisplayMember = "PurchaseOrderNumber";
}
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.SalesOrderDetail;
}
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(true);
}
catch (OptimisticConcurrencyException)
{
// Resolve the concurrently conflict by refreshing the
// object context before saving changes.
context.Refresh(RefreshMode.ClientWins, order.SalesOrderDetail);
// Resave changes in the object context.
context.SaveChanges(true);
}
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();
}
}
}
}
참고 항목
작업
방법: Windows Presentation Foundation 컨트롤에 개체 바인딩(Entity Framework)
방법: 프로젝트 데이터 소스로 개체 추가(Entity Framework)
개념
컨트롤에 개체 바인딩(Entity Framework)
컨트롤에 엔터티 데이터 바인딩(응용 프로그램 시나리오)