ObjectDataSource.InsertMethod 속성
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
컨트롤이 데이터를 삽입하기 위해 호출하는 메서드 또는 함수의 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 의 이름을 나타내는 문자열입니다. 기본값은 빈 문자열("")입니다.
예제
이 섹션에는 두 가지 코드 예제가 포함되어 있습니다. 첫 번째 코드 예제에서는 비즈니스 개체와 DetailsView 컨트롤을 사용하여 ObjectDataSource 데이터를 삽입하는 방법을 보여 줍니다. 두 번째 코드 예제에서는 첫 번째 코드 예제에서 사용되는 중간 계층 비즈니스 개체의 예를 제공합니다.
다음 코드 예제에서는 비즈니스 개체와 컨트롤을 사용 하 여 데이터를 삽입 하는 컨트롤을 DetailsView 사용 ObjectDataSource 하는 방법을 보여 줍니다. 처음에는 DetailsView 자동으로 생성된 삽입 단추와 함께 새 NorthwindEmployee 레코드가 표시됩니다. 컨트롤의 DetailsView 필드에 데이터를 입력한 후 삽입 단추를 클릭합니다. 이 속성은 InsertMethod 삽입 작업을 수행하는 메서드를 식별합니다.
이 예제 UpdateEmployeeInfo 에서 메서드는 삽입을 수행하는 데 사용되지만 데이터를 삽입하려면 매개 변수가 필요합니다 NorthwindEmployee . 이러한 이유로 컨트롤이 자동으로 전달하는 문자열 DetailsView 컬렉션으로는 충분하지 않습니다.
NorthwindEmployeeInserting 대리자는 ObjectDataSourceMethodEventHandler 이벤트를 처리 Inserting 하고 작업이 진행되기 전에 Insert 입력 매개 변수를 조작할 수 있는 개체입니다. 메서드에 UpdateEmployeeInfo 매개 변수로 개체가 필요하기 NorthwindEmployee 때문에 문자열 컬렉션을 사용하여 개체가 만들어지고 메서드에서 예상하는 InputParameters 매개 변수 이름(ne)을 사용하여 컬렉션에 추가됩니다. 기존 중간 계층 개체를 컨트롤과 함께 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 개체와 InsertMethod 연결된 개체의 ObjectDataSourceView 속성에 ObjectDataSource 위임합니다.
개체 수명
속성으로 InsertMethod 식별되는 메서드는 인스턴스 메서드 또는 static (Shared Visual Basic의 경우) 메서드일 수 있습니다. 인스턴스 메서드인 경우 속성에 지정된 InsertMethod 메서드가 호출될 때마다 비즈니스 개체가 만들어지고 제거됩니다. 속성이 ObjectCreated 호출되기 전에 비즈니스 개체와 함께 작동하도록 이벤트 및 ObjectCreating 이벤트를 처리할 InsertMethod 수 있습니다. 속성에 ObjectDisposing 지정된 메서드가 호출된 후 발생하는 이벤트를 처리할 DeleteMethod 수도 있습니다. 비즈니스 개체가 인터페이스를 구현하는 IDisposable 경우 개체가 Dispose 제거되기 전에 메서드가 호출됩니다. Visual Basic에서 메서드가Sharedstatic 있으면 비즈니스 개체가 만들어지지 않으며 , ObjectCreating및 ObjectDisposing 이벤트를 처리ObjectCreated할 수 없습니다.
매개 변수 병합
매개 변수는 다음 세 가지 소스에서 컬렉션에 추가 InsertParameters 됩니다.
데이터 바인딩된 컨트롤에서 런타임에.
요소에서
InsertParameters선언적으로.프로그래밍 방식으로 메서드에서.
Inserting
먼저 데이터 바인딩된 컨트롤에서 생성된 모든 매개 변수가 컬렉션에 InsertParameters 추가됩니다. 예를 들어 컨트롤이 ObjectDataSource 열 Name 이 Number있는 컨트롤에 바인딩 GridView 된 경우 컬렉션에 대한 Name 매개 변수 및 Number 컬렉션에 추가되는 매개 변수입니다. 이러한 매개 변수의 데이터 형식은 .입니다 string. 다음으로 요소에 나열된 매개 변수가 InsertParameters 추가됩니다. 요소의 InsertParameters 매개 변수가 컬렉션에 이미 있는 매개 변수와 동일한 이름을 가진 경우 요소에 InsertParameters 지정된 매개 변수와 일치하도록 기존 매개 변수가 수정됩니다 InsertParameters . 일반적으로 매개 변수의 데이터 형식을 수정하는 데 사용됩니다. 마지막으로 메서드가 실행되기 전에 Insert 발생하는 이벤트에서 매개 변수를 Inserting 프로그래밍 방식으로 추가하고 제거할 수 있습니다. 매개 변수가 병합된 후 메서드가 확인됩니다. 메서드 확인은 다음 섹션에서 설명합니다.
중요합니다
클라이언트에서 받은 매개 변수 값의 유효성을 검사해야 합니다. 런타임은 매개 변수 값을 속성으로 대체합니다 InsertMethod .
메서드 확인
메서드가 Insert 호출되면 데이터 바인딩된 컨트롤의 데이터 필드, 요소에서 InsertParameters 선언적으로 생성된 매개 변수 및 이벤트 처리기에 추가 Inserting 된 매개 변수가 모두 병합됩니다. (자세한 내용은 이전 섹션을 참조하세요.) 그런 다음 개체가 ObjectDataSource 호출할 메서드를 찾으려고 시도합니다. 먼저 속성에 지정된 이름을 가진 하나 이상의 메서드를 InsertMethod 찾습니다. 일치하는 항목이 없으면 예외가 InvalidOperationException throw됩니다. 일치 항목이 발견되면 일치하는 매개 변수 이름을 찾습니다. 예를 들어 속성에 지정된 TypeName 형식에 이름이 InsertARecord두 개의 메서드가 있다고 가정합니다. 하나는 InsertARecord 하나의 매개 변수를 가지며 다른 IDInsertARecord 매개 변수에는 두 개의 매개 변수가 Name 있습니다Number. 컬렉션에 InsertParameters 이름이 지정된 ID매개 변수가 하나뿐이 InsertARecord 면 매개 변수만 ID 있는 메서드가 호출됩니다. 메서드를 확인할 때 매개 변수 형식이 체크 인되지 않습니다. 매개 변수의 순서는 중요하지 않습니다.
속성이 DataObjectTypeName 설정되면 메서드가 다른 방식으로 확인됩니다. 속성 ObjectDataSource 에 지정된 형식의 매개 변수를 하나 사용하는 속성에 지정된 InsertMethod 이름을 가진 메서드를 DataObjectTypeName 찾습니다. 이 경우 매개 변수의 이름은 중요하지 않습니다.