ObjectDataSource.InsertMethod 属性

定义

获取或设置由 ObjectDataSource 控件调用以插入数据的方法或函数的名称。Gets or sets the name of the method or function that the ObjectDataSource control invokes to insert data.

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 用于插入数据的方法或函数的名称。A string that represents the name of the method or function that the ObjectDataSource uses to insert data. 默认值为空字符串("")。The default is an empty string ("").

示例

本部分包含两个代码示例。This section contains two code examples. 第一个代码示例演示如何将ObjectDataSource对象与业务对象DetailsView和控件结合使用来插入数据。The first code example demonstrates how to use an ObjectDataSource object with a business object and a DetailsView control to insert data. 第二个代码示例提供了在第一个代码示例中使用的中间层业务对象的示例。The second code example provides an example of the middle-tier business object that is used in the first code example.

下面的代码示例演示如何将ObjectDataSource控件与业务对象DetailsView和控件结合使用来插入数据。The following code example demonstrates how to use an ObjectDataSource control with a business object and a DetailsView control to insert data. 最初, DetailsView会显示一个新NorthwindEmployee记录和一个自动生成的 "插入" 按钮。Initially, the DetailsView displays a new NorthwindEmployee record, along with an automatically generated Insert button. DetailsView控件的字段中输入数据后, 单击 "插入" 按钮。After you enter data into the fields of the DetailsView control, click the Insert button. InsertMethod属性标识执行插入操作的方法。The InsertMethod property identifies which method performs the insert operation.

在此示例中, UpdateEmployeeInfo方法用于执行插入; 但是, 它需要一个NorthwindEmployee参数来插入数据。In this example, the UpdateEmployeeInfo method is used to perform an insert; however, it requires a NorthwindEmployee parameter to insert the data. 出于此原因, DetailsView控件自动传递的字符串集合是不够的。For this reason, the collection of strings that the DetailsView control passes automatically is not sufficient. 委托是处理Inserting事件并使Insert你能够在操作继续之前操作输入参数的对象。ObjectDataSourceMethodEventHandler NorthwindEmployeeInsertingThe NorthwindEmployeeInserting delegate is an ObjectDataSourceMethodEventHandler object that handles the Inserting event and enables you to manipulate the input parameters before the Insert operation proceeds. 由于方法需要对象作为参数, 因此使用字符串集合创建一个对象, InputParameters并使用该方法所需的参数名称 (ne) 将其添加到集合中。 NorthwindEmployee UpdateEmployeeInfoBecause the UpdateEmployeeInfo method requires a NorthwindEmployee object as a parameter, one is created using the collection of strings and is added to the InputParameters collection using a parameter name (ne) that the method expects. 使用现有的中间层对象作为数据源时, 可以执行如下所述的步骤, 这些类型和方法不是专门用于ObjectDataSource控件的。You might perform steps like these when using an existing middle-tier object as a data source with types and methods that are not designed specifically for use with the ObjectDataSource control.

执行操作时, 将调用InsertMethod由属性标识的方法。 InsertWhen the Insert operation is performed, the method that is identified by the InsertMethod property is called. 如果对象的InsertParameters Insert方法具有包含参数的方法签名, 则集合必须包含名称与方法签名参数匹配的参数, 才能成功完成该方法。 InsertIf the Insert method of the object has a method signature that includes parameters, the InsertParameters collection must contain a parameter with names that match the method signature parameters for the Insert method to complete successfully.

<%@ 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>

下面的代码示例提供了前面的代码示例使用的中间层业务对象的示例。The following code example provides an example of a middle-tier business object that the preceding code example uses. 此代码示例包含两个基本类:The code example consists of two basic classes:

  • EmployeeLogic类, 该类是封装业务逻辑的无状态类。The EmployeeLogic class, which is a stateless class that encapsulates business logic.

  • NorthwindEmployee类, 该类是一个模型类, 其中只包含从数据层加载和保存数据所需的基本功能。The NorthwindEmployee class, which is a model class that contains only the basic functionality that is required to load and persist data from the data tier.

提供一个NorthwindDataException额外的类作为便利。An additional NorthwindDataException class is provided as a convenience. 若要获取完整的工作示例, 必须编译并使用这些类。For a complete working example, you must compile and use these classes. UpdateEmployeeInfo方法未完全实现, 因此当您试验此示例时, 不会将数据插入 Northwind 商贸数据库中。The UpdateEmployeeInfo method is not completely implemented, so you will not insert data into the Northwind Traders database when you experiment with this example.

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

注解

假定业务对象每次插入一条记录, 而不是在批处理中插入数据。The business object is assumed to insert data one record at a time, rather than in a batch.

属性委托ObjectDataSourceView InsertMethod给与ObjectDataSource对象关联的对象的属性。 InsertMethodThe InsertMethod property delegates to the InsertMethod property of the ObjectDataSourceView object that is associated with the ObjectDataSource object.

对象生存期Object Lifetime

InsertMethod属性标识的方法可以是实例方法, static也可以是 (Shared在 Visual Basic) 方法。The method that is identified by the InsertMethod property can be an instance method or a static (Shared in Visual Basic) method. 如果它是实例方法, 则每次调用InsertMethod属性指定的方法时都会创建并销毁业务对象。If it is an instance method, the business object is created and destroyed each time the method specified by the InsertMethod property is called. 您可以处理ObjectCreatedObjectCreating事件, 在调用InsertMethod属性之前使用业务对象。You can handle the ObjectCreated and ObjectCreating events to work with the business object before the InsertMethod property is called. 你还可以处理在ObjectDisposing调用DeleteMethod由属性指定的方法之后引发的事件。You can also handle the ObjectDisposing event that is raised after the method that is specified by the DeleteMethod property is called. 如果业务对象实现IDisposable接口Dispose , 则在销毁对象之前调用方法。If the business object implements the IDisposable interface, the Dispose method is called before the object is destroyed. 如果该方法为static (Shared在 Visual Basic 中), 则永远不会创建业务对象, 也不ObjectCreatedObjectCreating处理、 ObjectDisposing和事件。If the method is static (Shared in Visual Basic), the business object is never created and you cannot handle the ObjectCreated, ObjectCreating, and ObjectDisposing events.

参数合并Parameter Merging

将参数添加到集合InsertParameters中的三个源:Parameters are added to the InsertParameters collection from three sources:

  • 在运行时从数据绑定控件。From the data-bound control, at run time.

  • InsertParameters从元素中以声明方式。From the InsertParameters element, declaratively.

  • 以编程方式从方法。InsertingFrom the Inserting method, programmatically.

首先, 将从数据绑定控件生成的所有参数添加到InsertParameters集合中。First, any parameters that are generated from data-bound controls are added to the InsertParameters collection. ObjectDataSource例如, 如果将控件绑定GridView到具有列NameNumber的控件, 则NameNumber的参数将添加到集合中。For example, if the ObjectDataSource control is bound to a GridView control that has the columns Name and Number, the parameters for Name and Number are added to the collection. 这些参数的数据类型为stringThe data type of these parameters is string. 接下来, 添加InsertParameters元素中列出的参数。Next, the parameters that are listed in the InsertParameters element are added. 如果找到了InsertParameters元素中与InsertParameters集合中已有的参数同名的参数, 则会修改现有参数, 使其与InsertParameters元素中指定的参数匹配。If a parameter in the InsertParameters element is found with the same name as a parameter that is already in the InsertParameters collection, the existing parameter is modified to match the parameter that is specified in the InsertParameters element. 通常, 这用于修改参数中数据的类型。Typically, this is used to modify the type of the data in the parameter. 最后, 你可以通过编程方式在运行Inserting Insert方法之前, 在事件中添加和移除参数。Finally, you can programmatically add and remove parameters in the Inserting event, which occurs before the Insert method is run. 合并参数后, 解析方法。The method is resolved after the parameters are merged. 下一节将讨论方法解析。Method resolution is discussed in the next section.

重要

你应验证从客户端接收的任何参数值。You should validate any parameter value that you receive from the client. 运行时只需将参数值替换为InsertMethod属性。The runtime simply substitutes the parameter value into the InsertMethod property.

方法解析Method Resolution

调用方法时, 数据绑定控件中的数据字段、在InsertParameters元素中以声明方式创建的参数以及在Inserting事件处理程序中添加的参数都将合并。 InsertWhen the Insert method is called, the data fields from the data-bound control, the parameters that were created declaratively in the InsertParameters element, and the parameters that were added in the Inserting event handler are all merged. (有关详细信息, 请参阅前面的部分。)然后ObjectDataSource , 对象会尝试查找要调用的方法。(For more information, see the preceding section.) The ObjectDataSource object then attempts to find a method to call. 首先, 它会查找一个或多个具有在InsertMethod属性中指定的名称的方法。First, it looks for one or more methods with the name that is specified in the InsertMethod property. 如果未找到匹配项, InvalidOperationException则会引发异常。If no match is found, an InvalidOperationException exception is thrown. 如果找到匹配项, 则它将查找匹配的参数名称。If a match is found, it then looks for matching parameter names. 例如, 假设TypeName属性指定的类型有两个名为InsertARecord的方法。For example, suppose a type that is specified by the TypeName property has two methods named InsertARecord. 一个InsertARecord InsertARecord 参数为,另Name一个参数Number具有两个参数: 和。 IDOne InsertARecord has one parameter, ID, and the other InsertARecord has two parameters, Name and Number. 如果集合仅包含一个名为ID的参数, InsertARecord则将调用只ID包含参数的方法。 InsertParametersIf the InsertParameters collection has only one parameter named ID, the InsertARecord method with just the ID parameter is called. 解析方法时未检查参数类型。The type of the parameter is not checked in resolving the methods. 参数的顺序并不重要。The order of the parameters does not matter.

如果设置了属性, 则会以不同的方式解析方法。 DataObjectTypeNameIf the DataObjectTypeName property is set, the method is resolved in a different way. 查找具有在属性中指定的名称的方法, 该属性采用在DataObjectTypeName属性中指定的类型的一个参数。 InsertMethod ObjectDataSourceThe ObjectDataSource looks for a method with the name that is specified in the InsertMethod property that takes one parameter of the type that is specified in the DataObjectTypeName property. 在这种情况下, 参数名称并不重要。In this case, the name of the parameter does not matter.

适用于

另请参阅