다음을 통해 공유


데이터베이스에 바인딩

업데이트: 2007년 11월

일반적으로 웹 응용 프로그램에는 Microsoft SQL Server, Microsoft Access, Oracle, OLEDB 또는 ODBC 데이터 저장소 같은 관계형 데이터베이스의 데이터가 표시됩니다. ASP.NET에서 제공하는 LinqDataSourceSqlDataSource 컨트롤을 사용하면 데이터베이스의 데이터에 컨트롤을 바인딩하는 작업을 간소화할 수 있습니다.

LinqDataSource 컨트롤

LinqDataSource 컨트롤을 사용하면 선언 태그를 통해 ASP.NET 웹 페이지에서 LINQ(통합 언어 쿼리)를 사용하여 데이터 개체의 데이터를 검색 및 수정할 수 있습니다. 이 컨트롤은 선택, 업데이트, 삽입 및 삭제 명령의 자동 생성을 지원합니다. 또한 이 컨트롤은 정렬, 필터링 및 페이징 기능을 지원합니다.

LinqDataSource 컨트롤을 사용하여 데이터베이스의 데이터와 상호 작용할 때는 LinqDataSource 컨트롤을 데이터베이스에 직접 연결하지 않습니다. 대신 데이터베이스 및 테이블을 나타내는 엔터티 클래스와 상호 작용합니다. 개체 관계형 디자이너를 통해 또는 SqlMetal.exe 유틸리티를 실행하여 엔터티 클래스를 생성할 수 있습니다. 자세한 내용은 O/R 디자이너(개체 관계형 디자이너)코드 생성 도구(SqlMetal.exe)을 참조하십시오.

사용자가 만드는 엔터티 클래스는 일반적으로 웹 응용 프로그램의 App_Code 폴더에 배치됩니다. O/R 디자이너 또는 SqlMetal.exe 유틸리티에서는 데이터베이스를 나타내는 클래스 하나와 데이터베이스의 각 테이블에 대한 클래스 하나를 생성합니다.

ContextTypeName 속성을 데이터베이스를 나타내는 클래스 이름으로 설정하여 LinqDataSource 컨트롤을 데이터베이스 클래스에 연결합니다. TableName 속성을 데이터 테이블을 나타내는 클래스 이름으로 설정하여 LinqDataSource 컨트롤을 특정 테이블에 연결합니다. 예를 들어 AdventureWorks 데이터베이스의 Contacts 테이블에 연결하려면 ContextTypeName 속성을 AdventureWorksDataContext 또는 데이터베이스 개체에 대해 지정하는 임의의 이름 같은 클래스 이름으로 설정합니다. TableName 속성을 Contacts로 설정합니다.

다음 예제에서는 Products 테이블에서 데이터를 검색하는 LinqDataSource 컨트롤을 보여 줍니다. 이 컨트롤은 데이터의 삽입, 업데이트 및 삭제를 지원하는 명령을 자동으로 생성합니다. DetailsView 컨트롤은 데이터를 표시하며 사용자가 데이터 레코드를 수정할 수 있도록 하는 단추를 만듭니다.

<asp:LinqDataSource 
    ContextTypeName="ExampleDataContext" 
    TableName="Products" 
    EnableUpdate="true"
    EnableInsert="true"
    EnableDelete="true"
    ID="LinqDataSource1" 
    >
</asp:LinqDataSource>
<asp:DetailsView 
    DataKeyNames="ProductID"
    AutoGenerateEditButton="true"
    AutoGenerateDeleteButton="true"
    AutoGenerateInsertButton="true"
    AllowPaging="true"
    DataSourceID="LinqDataSource1"
    ID="GridView1" 
    >
</asp:DetailsView>
<asp:LinqDataSource 
    ContextTypeName="ExampleDataContext" 
    TableName="Products" 
    EnableUpdate="true"
    EnableInsert="true"
    EnableDelete="true"
    ID="LinqDataSource1" 
    >
</asp:LinqDataSource>
<asp:DetailsView 
    DataKeyNames="ProductID"
    AutoGenerateEditButton="true"
    AutoGenerateDeleteButton="true"
    AutoGenerateInsertButton="true"
    AllowPaging="true"
    DataSourceID="LinqDataSource1"
    ID="GridView1" 
    >
</asp:DetailsView>

자세한 내용은 LinqDataSource 웹 서버 컨트롤 개요를 참조하십시오.

SqlDataSource 컨트롤

SqlDataSource 컨트롤은 웹 응용 프로그램에서 데이터베이스에 대한 직접 연결을 나타냅니다. GridView, DetailsViewFormView 같은 데이터 바인딩된 컨트롤에서는 SqlDataSource 컨트롤을 사용하여 자동으로 데이터를 검색하고 수정할 수 있습니다. 데이터 선택, 삽입, 업데이트 및 삭제 명령을 SqlDataSource 컨트롤의 일부로 지정하면 이러한 작업이 자동으로 수행됩니다. 코드(예: System.Data 네임스페이스에서 클래스를 사용하는 ADO.NET 코드)를 작성하지 않고도 연결을 만들 수 있으며 데이터베이스를 쿼리하고 업데이트하는 명령을 지정할 수 있습니다.

다음 코드 예제에서는 데이터를 검색, 업데이트 및 삭제하기 위해 SqlDataSource 컨트롤에 바인딩된 GridView 컨트롤을 보여 줍니다.

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>GridView Edit Example</title>
</head>
<body>
    <form id="form1" >

      <h3>GridView Edit Example</h3>

      <!-- The GridView control automatically sets the columns     -->
      <!-- specified in the datakeynames property as read-only.    -->
      <!-- No input controls are rendered for these columns in     -->
      <!-- edit mode.                                              -->
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        autogeneratedeletebutton="true"
        autogenerateeditbutton="true"
        datakeynames="CustomerID"  
        >
      </asp:gridview>

      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSqlDataSource"  
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        updatecommand="Update Customers SET CompanyName=@CompanyName, Address=@Address, City=@City, PostalCode=@PostalCode, Country=@Country WHERE (CustomerID = @CustomerID)"
        deletecommand="Delete from Customers where CustomerID = @CustomerID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        >
      </asp:sqldatasource>

    </form>
  </body>
</html>

<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>GridView Edit Example</title>
</head>
<body>
    <form id="form1" >

      <h3>GridView Edit Example</h3>

      <!-- The GridView control automatically sets the columns     -->
      <!-- specified in the datakeynames property as read-only.    -->
      <!-- No input controls are rendered for these columns in     -->
      <!-- edit mode.                                              -->
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        autogeneratedeletebutton="true"
        autogenerateeditbutton="true"
        datakeynames="CustomerID"  
        >
      </asp:gridview>

      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSqlDataSource"  
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        updatecommand="Update Customers SET CompanyName=@CompanyName, Address=@Address, City=@City, PostalCode=@PostalCode, Country=@Country WHERE (CustomerID = @CustomerID)"
        deletecommand="Delete from Customers where CustomerID = @CustomerID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        >
      </asp:sqldatasource>

    </form>
  </body>
</html>

SqlDataSource 컨트롤은 데이터베이스에 직접 연결하므로 2 계층 데이터 모델을 구현합니다. 데이터 검색 및 업데이트를 수행하는 중간 계층 비즈니스 개체에 바인딩해야 할 경우에는 ObjectDataSource 컨트롤을 사용할 수 있습니다. 자세한 내용은 비즈니스 개체에 바인딩을 참조하십시오.

SqlDataSource 컨트롤에 대한 자세한 내용은 SqlDataSource 웹 서버 컨트롤 개요를 참조하십시오.

Microsoft Access 데이터베이스에 바인딩

ASP.NET에서 제공하는 AccessDataSource 컨트롤을 사용하면 Microsoft Access 데이터베이스 파일(.mdb 파일)에 연결하는 작업을 간소화할 수 있습니다. AccessDataSource 클래스는 SqlDataSource 클래스에서 상속되고 System.Data.OleDb .NET Framework 데이터 공급자 및 Microsoft.Jet.OLEDB.4.0 OLE DB 공급자를 사용하여 자동으로 .mdb 파일에 연결합니다. Access 데이터베이스에 연결하려면 파일 경로를 DataFile 속성으로 제공합니다. AccessDataSource 컨트롤은 Microsoft Access 데이터베이스에 연결하는 방식이 다르다는 점을 제외하면 SqlDataSource 컨트롤과 작동 방식이 같습니다. 자세한 내용은 AccessDataSource 웹 서버 컨트롤을 사용하여 데이터 검색을 참조하십시오.

참고 항목

개념

ASP.NET 데이터 액세스 개요

LinqDataSource 웹 서버 컨트롤 개요

SqlDataSource 웹 서버 컨트롤 개요

AccessDataSource 웹 서버 컨트롤을 사용하여 데이터 검색