ObjectDataSource.InsertMethod 屬性

定義

取得或設定 ObjectDataSource 控制項叫用以插入資料之方法或函式的名稱。

public:
 property System::String ^ InsertMethod { System::String ^ get(); void set(System::String ^ value); };
public string InsertMethod { get; set; }
member this.InsertMethod : string with get, set
Public Property InsertMethod As String

屬性值

字串,表示 ObjectDataSource 用於插入資料之方法或函式的名稱。 預設為空字串 ("")。

範例

本節包含兩個程式碼範例。 第一個程式碼範例示範如何使用 ObjectDataSource 物件搭配商務物件和 DetailsView 控制項來插入資料。 第二個程式碼範例提供第一個程式碼範例中使用的仲介層商務物件範例。

下列程式碼範例示範如何使用 ObjectDataSource 控制項搭配商務物件和 DetailsView 控制項來插入資料。 一開始,會顯示 DetailsView 新的 NorthwindEmployee 記錄,以及自動產生的 [ 插入 ] 按鈕。 將資料輸入控制項的 DetailsView 欄位之後,按一下 [ 插入 ] 按鈕。 屬性 InsertMethod 會識別執行插入作業的方法。

在此範例中 UpdateEmployeeInfo ,方法是用來執行插入;不過,它需要 NorthwindEmployee 參數來插入資料。 基於這個理由,控制項自動傳遞的 DetailsView 字串集合不夠。 委派 NorthwindEmployeeInsertingObjectDataSourceMethodEventHandler 處理事件的物件 Inserting ,可讓您在作業繼續之前 Insert 操作輸入參數。 UpdateEmployeeInfo因為方法需要 NorthwindEmployee 物件做為參數,所以使用字串集合建立,並使用方法預期的參數名稱 (ne) 新增至 InputParameters 集合。 使用現有的仲介層物件做為資料來源時,您可能會執行這些步驟,這些物件的類型和方法並非特別設計來搭配控制項使用 ObjectDataSource

Insert執行作業時,會呼叫 屬性所識別 InsertMethod 的方法。 Insert如果 物件的方法簽章包含參數的方法簽章, InsertParameters 集合必須包含名稱符合方法方法簽章參數 Insert 的參數,才能順利完成。

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Import namespace="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private void NorthwindEmployeeInserting(object source, ObjectDataSourceMethodEventArgs e)
{
  // The business object expects a custom type. Build it
  // and add it to the parameters collection.
  
  IDictionary paramsFromPage = e.InputParameters;

  NorthwindEmployee ne = new NorthwindEmployee();

  ne.FirstName  = paramsFromPage["FirstName"].ToString();
  ne.LastName   = paramsFromPage["LastName"].ToString();
  ne.Title      = paramsFromPage["Title"].ToString();
  ne.Courtesy   = paramsFromPage["Courtesy"].ToString();
  ne.Supervisor = Int32.Parse(paramsFromPage["Supervisor"].ToString());

  paramsFromPage.Clear();
  paramsFromPage.Add("ne", ne);
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:detailsview
          id="DetailsView1"
          runat="server"
          autogenerateinsertbutton="True"
          datasourceid="ObjectDataSource1">
        </asp:detailsview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetEmployee"
          insertmethod="UpdateEmployeeInfo"
          oninserting="NorthwindEmployeeInserting"
          typename="Samples.AspNet.CS.EmployeeLogic"
          >
          <selectparameters>
            <asp:parameter name="anID" defaultvalue="-1" />
          </selectparameters>
        </asp:objectdatasource>

    </form>
  </body>
</html>
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
<%@ Import namespace="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private Sub NorthwindEmployeeInserting(source As Object, e As ObjectDataSourceMethodEventArgs)

  ' The GridView control passes an array of strings in the parameters
  ' collection because that is the type it knows how to work with.
  ' However, the business object expects a custom type. Build it
  ' and add it to the parameters collection.
  Dim paramsFromPage As IDictionary = e.InputParameters

  Dim ne As New NorthwindEmployee()
  ne.FirstName  = paramsFromPage("FirstName").ToString()
  ne.LastName   = paramsFromPage("LastName").ToString()
  ne.Title      = paramsFromPage("Title").ToString()
  ne.Courtesy   = paramsFromPage("Courtesy").ToString()
  ne.Supervisor = Int32.Parse(paramsFromPage("Supervisor").ToString())
  
  paramsFromPage.Clear()
  paramsFromPage.Add("ne", ne)
End Sub ' NorthwindEmployeeInserting

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - VB Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:detailsview
          id="DetailsView1"
          runat="server"
          autogenerateinsertbutton="True"
          datasourceid="ObjectDataSource1">
        </asp:detailsview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetEmployee"
          insertmethod="UpdateEmployeeInfo"
          oninserting="NorthwindEmployeeInserting"
          typename="Samples.AspNet.VB.EmployeeLogic" >
          <selectparameters>
            <asp:parameter name="anID" defaultvalue="-1" />
          </selectparameters>
        </asp:objectdatasource>

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

下列程式碼範例提供上述程式碼範例所使用的仲介層商務物件範例。 程式碼範例包含兩個基本類別:

  • 類別 EmployeeLogic ,這是封裝商務邏輯的無狀態類別。

  • 類別 NorthwindEmployee ,這是一個模型類別,其中包含從資料層載入和保存資料所需的基本功能。

為了方便起見,會提供額外的 NorthwindDataException 類別。 如需完整的工作範例,您必須編譯並使用這些類別。 方法 UpdateEmployeeInfo 未完全實作,因此當您實驗此範例時,將不會將資料插入 Northwind Traders 資料庫。

namespace Samples.AspNet.CS {

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
  //
  // EmployeeLogic is a stateless business object that encapsulates
  // the operations you can perform on a NorthwindEmployee object.
  //
  public class EmployeeLogic {

    // Returns a collection of NorthwindEmployee objects.
    public static ICollection GetAllEmployees () {
      ArrayList al = new ArrayList();

      ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];

      SqlDataSource sds
        = new SqlDataSource(cts.ConnectionString,
                            "SELECT EmployeeID FROM Employees");
      try {
        IEnumerable IDs = sds.Select(DataSourceSelectArguments.Empty);

        // Iterate through the Enumeration and create a
        // NorthwindEmployee object for each ID.
        IEnumerator enumerator = IDs.GetEnumerator();
        while (enumerator.MoveNext()) {
          // The IEnumerable contains DataRowView objects.
          DataRowView row = enumerator.Current as DataRowView;
          string id = row["EmployeeID"].ToString();
          NorthwindEmployee nwe = new NorthwindEmployee(id);
          // Add the NorthwindEmployee object to the collection.
          al.Add(nwe);
        }
      }
      finally {
        // If anything strange happens, clean up.
        sds.Dispose();
      }

      return al;
    }

    public static NorthwindEmployee GetEmployee(object anID) {
      if (anID.Equals("-1") ||
          anID.Equals(DBNull.Value) ) {
        return new NorthwindEmployee();
      }
      else {
        return new NorthwindEmployee(anID);
      }
    }

    public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
      bool retval = ne.Save();
      if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
    }

    public static void DeleteEmployee(NorthwindEmployee ne) {
      bool retval = ne.Delete();
      if (! retval) { throw new NorthwindDataException("DeleteEmployee failed."); }
    }

    // And so on...
  }

  public class NorthwindEmployee {

    public NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = "";
      firstName = "";
      title="";
      titleOfCourtesy = "";
      reportsTo = -1;
    }

    public NorthwindEmployee (object anID) {
      this.ID = anID;

      SqlConnection conn
        = new SqlConnection (ConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString);
      SqlCommand sc =
        new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
                       " FROM Employees " +
                       " WHERE EmployeeID = @empId",
                       conn);
      // Add the employee ID parameter and set its value.
      sc.Parameters.Add(new SqlParameter("@empId",SqlDbType.Int)).Value = Int32.Parse(anID.ToString());
      SqlDataReader sdr = null;

      try {
        conn.Open();
        sdr = sc.ExecuteReader();

        // Only loop once.
        if (sdr != null && sdr.Read()) {
          // The IEnumerable contains DataRowView objects.
          this.firstName        = sdr["FirstName"].ToString();
          this.lastName         = sdr["LastName"].ToString();
          this.title            = sdr["Title"].ToString();
          this.titleOfCourtesy  = sdr["TitleOfCourtesy"].ToString();
          if (! sdr.IsDBNull(4)) {
            this.reportsTo        = sdr.GetInt32(4);
          }
        }
        else {
          throw new NorthwindDataException("Data not loaded for employee id.");
        }
      }
      finally {
        try {
          if (sdr != null) sdr.Close();
          conn.Close();
        }
        catch (SqlException) {
          // Log an event in the Application Event Log.
          throw;
        }
      }
    }

    private object ID;
    public string EmpID {
      get { return ID.ToString();  }
    }

    private string lastName;
    public string LastName {
      get { return lastName; }
      set { lastName = value; }
    }

    private string firstName;
    public string FirstName {
      get { return firstName; }
      set { firstName = value;  }
    }

    public string FullName {
      get { return FirstName + " " + LastName; }
    }

    private string title;
    public String Title {
      get { return title; }
      set { title = value; }
    }

    private string titleOfCourtesy;
    public string Courtesy {
      get { return titleOfCourtesy; }
      set { titleOfCourtesy = value; }
    }

    private int    reportsTo;
    public int Supervisor {
      get { return reportsTo; }
      set { reportsTo = value; }
    }

    public bool Save () {
      // Implement persistence logic.
      return true;
    }

    public bool Delete () {
      // Implement delete logic.
      return true;
    }
  }

  internal class NorthwindDataException: Exception {
    public NorthwindDataException(string msg) : base (msg) { }
  }
}
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet.VB

'
' EmployeeLogic is a stateless business object that encapsulates
' the operations you can perform on a NorthwindEmployee object.
'
Public Class EmployeeLogic

   ' Returns a collection of NorthwindEmployee objects.
   Public Shared Function GetAllEmployees() As ICollection

      Dim al As New ArrayList()

      Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")

      Dim sds As New SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees")

      Try
         Dim IDs As IEnumerable = sds.Select(DataSourceSelectArguments.Empty)

         ' Iterate through the Enumeration and create a
         ' NorthwindEmployee object for each ID.
         Dim enumerator As IEnumerator = IDs.GetEnumerator()
         While enumerator.MoveNext()
            ' The IEnumerable contains DataRowView objects.
            Dim row As DataRowView = CType(enumerator.Current,DataRowView)
            Dim id As String = row("EmployeeID").ToString()
            Dim nwe As New NorthwindEmployee(id)
            ' Add the NorthwindEmployee object to the collection.
            al.Add(nwe)
         End While
      Finally
         ' If anything strange happens, clean up.
         sds.Dispose()
      End Try

      Return al
   End Function 'GetAllEmployees


   Public Shared Function GetEmployee(anID As Object) As NorthwindEmployee
      If anID.Equals("-1") OrElse anID.Equals(DBNull.Value) Then
         Return New NorthwindEmployee()
      Else
         Return New NorthwindEmployee(anID)
      End If
   End Function 'GetEmployee


   Public Shared Sub UpdateEmployeeInfo(ne As NorthwindEmployee)
      Dim retval As Boolean = ne.Save()
      If Not retval Then
         Throw New NorthwindDataException("UpdateEmployee failed.")
      End If
   End Sub

   Public Shared Sub DeleteEmployee(ne As NorthwindEmployee)
      Dim retval As Boolean = ne.Delete()
      If Not retval Then
         Throw New NorthwindDataException("DeleteEmployee failed.")
      End If
   End Sub

   ' And so on...

End Class


Public Class NorthwindEmployee


   Public Sub New()
      ID = DBNull.Value
      lastName = ""
      firstName = ""
      title = ""
      titleOfCourtesy = ""
      reportsTo = - 1
   End Sub


   Public Sub New(anID As Object)
      Me.ID = anID

      Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")

      Dim conn As New SqlConnection(cts.ConnectionString)

      Dim sc As New SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " & _
                               " FROM Employees " & _
                               " WHERE EmployeeID = @empId", conn)

      ' Add the employee ID parameter and set its value.
      sc.Parameters.Add(New SqlParameter("@empId", SqlDbType.Int)).Value = Int32.Parse(anID.ToString())
      Dim sdr As SqlDataReader = Nothing

      Try
         conn.Open()
         sdr = sc.ExecuteReader()

         ' Only loop once.
         If Not (sdr Is Nothing) AndAlso sdr.Read() Then
            ' The IEnumerable contains DataRowView objects.
            Me.aFirstName = sdr("FirstName").ToString()
            Me.aLastName = sdr("LastName").ToString()
            Me.aTitle = sdr("Title").ToString()
            Me.titleOfCourtesy = sdr("TitleOfCourtesy").ToString()
            If Not sdr.IsDBNull(4) Then
               Me.reportsTo = sdr.GetInt32(4)
            End If
         Else
            Throw New NorthwindDataException("Data not loaded for employee id.")
         End If
      Finally
         Try
            If Not (sdr Is Nothing) Then
               sdr.Close()
            End If
            conn.Close()
         Catch se As SqlException
            ' Log an event in the Application Event Log.
            Throw
         End Try
      End Try
   End Sub

   Private ID As Object
   Public ReadOnly Property EmpID() As String
      Get
         Return ID.ToString()
      End Get
   End Property

   Private aLastName As String
   Public Property LastName() As String
      Get
         Return aLastName
      End Get
      Set
         aLastName = value
      End Set
   End Property

   Private aFirstName As String
   Public Property FirstName() As String
      Get
         Return aFirstName
      End Get
      Set
         aFirstName = value
      End Set
   End Property

   Public ReadOnly Property FullName() As String
      Get
         Return FirstName & " " & LastName
      End Get
   End Property

   Private aTitle As String
   Public Property Title() As String
      Get
         Return aTitle
      End Get
      Set
         aTitle = value
      End Set
   End Property

   Private titleOfCourtesy As String
   Public Property Courtesy() As String
      Get
         Return titleOfCourtesy
      End Get
      Set
         titleOfCourtesy = value
      End Set
   End Property

   Private reportsTo As Integer
   Public Property Supervisor() As Integer
      Get
         Return reportsTo
      End Get
      Set
         reportsTo = value
      End Set
   End Property

   Public Function Save() As Boolean

      ' Implement persistence logic.
      Return True

   End Function 'Save


   Public Function Delete() As Boolean

     ' Implement delete logic.
     Return True

   End Function 'Delete
End Class


Friend Class NorthwindDataException
   Inherits Exception

   Public Sub New(msg As String)
      MyBase.New(msg)
   End Sub
End Class

End Namespace

備註

商務物件會假設一次插入一筆記錄,而不是在批次中插入資料。

屬性 InsertMethod 會委派給 InsertMethodObjectDataSource 物件相關聯之 物件的 屬性 ObjectDataSourceView

物件存留期

屬性所 InsertMethod 識別的方法可以是 Visual Basic) 方法中的實例方法或 static (Shared 。 如果是實例方法,則每次呼叫 屬性所 InsertMethod 指定的方法時,都會建立和終結商務物件。 您可以處理 ObjectCreatedObjectCreating 事件,以在呼叫 屬性之前 InsertMethod 使用商務物件。 您也可以處理 ObjectDisposing 呼叫 屬性所 DeleteMethod 指定方法之後所引發的事件。 如果商務物件實作 IDisposable 介面,則會 Dispose 在物件終結之前呼叫 方法。 如果方法 static 在 Visual Basic) 中 Shared (,則永遠不會建立商務物件,而且您無法處理 ObjectCreatedObjectCreatingObjectDisposing 事件。

參數合併

參數會從三個來源新增至 InsertParameters 集合:

  • 從資料繫結控制項,在執行時間。

  • InsertParameters以宣告方式從 專案。

  • Inserting從 方法,以程式設計方式。

首先,從資料繫結控制項產生的任何參數都會新增至 InsertParameters 集合。 例如,如果 ObjectDataSource 控制項系結至 GridView 具有 Name 資料行和 Number 的控制項,則 和 Number 的參數 Name 會加入至集合中。 這些參數的資料類型為 string 。 接下來,會新增專案中列出的 InsertParameters 參數。 如果找到專案中的參數名稱與已經在集合中的 InsertParametersInsertParameters 參數相同,則會修改現有的參數,以符合專案中指定的 InsertParameters 參數。 一般而言,這是用來修改 參數中資料類型。 最後,您可以在 事件中 Inserting 以程式設計方式新增和移除參數,這會在執行 方法之前 Insert 發生。 方法會在合併參數之後解析。 下一節將討論方法解析。

重要

您應該驗證您從用戶端收到的任何參數值。 執行時間只會將參數值取代為 InsertMethod 屬性。

方法解析

Insert呼叫 方法時,來自資料繫結控制項的資料欄位、以宣告方式在 元素中 InsertParameters 建立的參數,以及事件處理常式中 Inserting 新增的參數全都會合並。 (如需詳細資訊,請參閱上一節。) 物件 ObjectDataSource 然後嘗試尋找要呼叫的方法。 首先,它會尋找具有 屬性中所指定名稱的 InsertMethod 一或多個方法。 如果找不到相符專案, InvalidOperationException 則會擲回例外狀況。 如果找到相符專案,則會尋找相符的參數名稱。 例如,假設 由 屬性指定的 TypeName 型別有兩個名為 InsertARecord 的方法。 其中一個 InsertARecord 參數有一個參數, IDInsertARecord 一個參數則有兩個參數, NameNumberInsertParameters如果集合只有一個名為 的參數 IDInsertARecord 則會呼叫只 ID 呼叫具有 參數的方法。 不會檢查參數的類型,無法解析方法。 參數的順序並不重要。

DataObjectTypeName如果已設定 屬性,方法會以不同的方式解析。 ObjectDataSource會尋找名稱在 屬性中指定的 InsertMethod 方法,該方法會採用 屬性中所指定之型別的 DataObjectTypeName 一個參數。 在此情況下,參數的名稱並不重要。

適用於

另請參閱