Asp.net-data-sources

提供:Dev Guides
移動先:案内検索

ASP.NET-データソース

データソースコントロールは、データバインドコントロールと対話し、複雑なデータバインディングプロセスを隠します。 これらは、データバインドコントロールにデータを提供し、挿入、削除、並べ替え、更新などの操作の実行をサポートするツールです。

各データソースコントロールは、特定のデータプロバイダーリレーショナルデータベース、XMLドキュメント、またはカスタムクラスをラップし、以下を支援します。

  • 接続の管理
  • データを選択する
  • ページング、キャッシュなどのプレゼンテーションの側面を管理する
  • データを操作する

ASP.NETには、SQL Server、ODBCまたはOLE DBサーバー、XMLファイル、およびビジネスオブジェクトからのデータにアクセスするための多くのデータソースコントロールがあります。

データの種類に基づいて、これらのコントロールは2つのカテゴリに分類できます。

  • 階層データソースコントロール
  • テーブルベースのデータソースコントロール

階層データに使用されるデータソースコントロールは次のとおりです。

  • XMLDataSource -スキーマ情報の有無にかかわらず、XMLファイルおよび文字列にバインドできます。
  • SiteMapDataSource -サイトマップ情報を提供するプロバイダーにバインドできます。

表形式データに使用されるデータソースコントロールは次のとおりです。

Data source controls Description
SqlDataSource It represents a connection to an ADO.NET data provider that returns SQL data, including data sources accessible via OLEDB and ODBC.
ObjectDataSource It allows binding to a custom .Net business object that returns data.
LinqdataSource It allows binding to the results of a Linq-to-SQL query (supported by ASP.NET 3.5 only).
AccessDataSource It represents connection to a Microsoft Access database.

データソースビュー

データソースビューは、DataSourceViewクラスのオブジェクトです。 並べ替え、フィルタリングなどのさまざまなデータ操作用にカスタマイズされたデータのビューを表します。

DataSourceViewクラスは、データソースコントロールの機能を定義するすべてのデータソースビュークラスの基本クラスとして機能します。

次の表に、DataSourceViewクラスのプロパティを示します。

Properties Description
CanDelete Indicates whether deletion is allowed on the underlying data source.
CanInsert Indicates whether insertion is allowed on the underlying data source.
CanPage Indicates whether paging is allowed on the underlying data source.
CanRetrieveTotalRowCount Indicates whether total row count information is available.
CanSort Indicates whether the data could be sorted.
CanUpdate Indicates whether updates are allowed on the underlying data source.
Events Gets a list of event-handler delegates for the data source view.
Name Name of the view.

次の表に、DataSourceViewクラスのメソッドを示します。

Methods Description
CanExecute Determines whether the specified command can be executed.
ExecuteCommand Executes the specific command.
ExecuteDelete Performs a delete operation on the list of data that the DataSourceView object represents.
ExecuteInsert Performs an insert operation on the list of data that the DataSourceView object represents.
ExecuteSelect Gets a list of data from the underlying data storage.
ExecuteUpdate Performs an update operation on the list of data that the DataSourceView object represents.
Delete Performs a delete operation on the data associated with the view.
Insert Performs an insert operation on the data associated with the view.
Select Returns the queried data.
Update Performs an update operation on the data associated with the view.
OnDataSourceViewChanged Raises the DataSourceViewChanged event.
RaiseUnsupportedCapabilitiesError Called by the RaiseUnsupportedCapabilitiesError method to compare the capabilities requested for an ExecuteSelect operation against those that the view supports.

SqlDataSourceコントロール

SqlDataSourceコントロールは、SQL ServerやOracleデータベースなどのリレーショナルデータベースへの接続、またはOLEDBまたはOpen Database Connectivity(ODBC)を介してアクセス可能なデータを表します。 データへの接続は、2つの重要なプロパティConnectionStringとProviderNameを介して行われます。

次のコードスニペットは、コントロールの基本的な構文を提供します。

<asp:SqlDataSource runat="server" ID="MySqlSource"
   ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName  %>'
   ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
   SelectionCommand= "SELECT *FROM EMPLOYEES"/>

<asp:GridView ID="GridView1" runat="server" DataSourceID="MySqlSource"/>

基になるデータでさまざまなデータ操作を構成することは、データソースコントロールのさまざまなプロパティ(プロパティグループ)に依存します。

次の表に、コントロールのプログラミングインターフェイスを提供するSqlDataSourceコントロールのプロパティの関連セットを示します。

Property Group Description

DeleteCommand,

DeleteParameters、

DeleteCommandType

Gets or sets the SQL statement, parameters, and type for deleting rows in the underlying data.

FilterExpression,

FilterParameters

Gets or sets the data filtering string and parameters.

InsertCommand,

InsertParameters、

InsertCommandType

Gets or sets the SQL statement, parameters, and type for inserting rows in the underlying database.

SelectCommand,

SelectParameters、

SelectCommandType

Gets or sets the SQL statement, parameters, and type for retrieving rows from the underlying database.
SortParameterName Gets or sets the name of an input parameter that the command’s stored procedure will use to sort data.

UpdateCommand,

UpdateParameters、

UpdateCommandType

Gets or sets the SQL statement, parameters, and type for updating rows in the underlying data store.

次のコードスニペットは、データ操作が有効なデータソースコントロールを示しています。

<asp:SqlDataSource runat="server" ID= "MySqlSource"
   ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName  %>'
   ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
   SelectCommand= "SELECT* FROM EMPLOYEES"
   UpdateCommand= "UPDATE EMPLOYEES SET LASTNAME=@lame"
   DeleteCommand= "DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid"
   FilterExpression= "EMPLOYEEID > 10">
   .....
   .....
</asp:SqlDataSource>

ObjectDataSourceコントロール

ObjectDataSourceコントロールを使用すると、ユーザー定義のクラスでメソッドの出力をデータバインドコントロールに関連付けることができます。 このクラスのプログラミングインターフェイスは、SqlDataSourceコントロールとほぼ同じです。

以下は、ビジネスオブジェクトをバインドする2つの重要な側面です。

  • バインド可能クラスには、デフォルトのコンストラクター、ステートレス、および選択、更新、挿入、および削除のセマンティクスにマップできるメソッドが必要です。
  • オブジェクトは一度に1つのアイテムを更新する必要があり、バッチ操作はサポートされていません。

このコントロールを操作する例に直接進みましょう。 学生クラスは、オブジェクトデータソースで使用されるクラスです。 このクラスには、学生ID、名前、市の3つのプロパティがあります。 デフォルトのコンストラクターと、データを取得するためのGetStudentsメソッドがあります。

学生クラス:

public class Student
{
   public int StudentID { get; set; }
   public string Name { get; set; }
   public string City { get; set; }

   public Student()
   { }

   public DataSet GetStudents()
   {
      DataSet ds = new DataSet();
      DataTable dt = new DataTable("Students");

      dt.Columns.Add("StudentID", typeof(System.Int32));
      dt.Columns.Add("StudentName", typeof(System.String));
      dt.Columns.Add("StudentCity", typeof(System.String));
      dt.Rows.Add(new object[] { 1, "M. H. Kabir", "Calcutta" });
      dt.Rows.Add(new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
      ds.Tables.Add(dt);

      return ds;
   }
}

次の手順を実行して、オブジェクトをオブジェクトデータソースにバインドし、データを取得します。

  • 新しいWebサイトを作成してください。
  • ソリューションエクスプローラーからプロジェクトを右クリックしてクラス(Students.cs)を追加し、クラステンプレートを追加して、上記のコードをその中に配置します。
  • アプリケーションがクラスへの参照を使用できるように、ソリューションを構築します。
  • オブジェクトデータソースコントロールをWebフォームに配置します。
  • オブジェクトを選択してデータソースを構成します。

オブジェクトの選択

  • データに対するさまざまな操作のデータメソッドを選択します。 この例では、メソッドは1つだけです。

データメソッドの選択

  • グリッドビューなどのデータバインドコントロールをページに配置し、オブジェクトデータソースをその基になるデータソースとして選択します。

データバインドコントロール

  • この段階で、デザインビューは次のようになります。

オブジェクトデータソース

*プロジェクトを実行すると、学生クラスからハードコードされたタプルが取得されます。

オブジェクトデータ結果

AccessDataSourceコントロール

AccessDataSourceコントロールは、Accessデータベースへの接続を表します。 SqlDataSourceコントロールに基づいており、よりシンプルなプログラミングインターフェイスを提供します。 次のコードスニペットは、データソースの基本的な構文を提供します。

<asp:AccessDataSource ID="AccessDataSource1 runat="server"
   DataFile="~/App_Data/ASPDotNetStepByStep.mdb" SelectCommand="SELECT* FROM  [DotNetReferences]">
</asp:AccessDataSource>

AccessDataSourceコントロールは、読み取り専用モードでデータベースを開きます。 ただし、挿入、更新、または削除操作の実行にも使用できます。 これは、ADO.NETコマンドとパラメーターコレクションを使用して行われます。

Accessデータベースはプレーンファイルであり、ASP.NETアプリケーションのデフォルトアカウントにはデータベースファイルへの書き込み権限がない可能性があるため、ASP.NETアプリケーション内からのAccessデータベースの更新には問題があります。