ObjectDataSource.SqlCacheDependency 속성
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
Microsoft SQL Server 캐시 종속성에 사용할 데이터베이스와 테이블을 나타내는 세미콜론으로 구분된 문자열을 가져오거나 설정합니다.
public:
virtual property System::String ^ SqlCacheDependency { System::String ^ get(); void set(System::String ^ value); };
public virtual string SqlCacheDependency { get; set; }
member this.SqlCacheDependency : string with get, set
Public Overridable Property SqlCacheDependency As String
속성 값
SQL Server 캐시 종속성에 사용할 데이터베이스 및 테이블을 나타내는 문자열입니다.
예제
이 섹션에는 두 가지 코드 예제가 포함되어 있습니다. 첫 번째 코드 예제에서는 SQL Server 캐시 종속성을 만들고 개체의 ObjectDataSource 속성을 설정하는 SqlCacheDependency 방법을 보여 줍니다. 두 번째 코드 예제에서는 개체를 사용하여 캐싱 및 필터링을 사용하도록 개체를 DataSet 반환하는 래퍼 메서드를 구현하는 ObjectDataSource 방법을 보여 줍니다.
다음 코드 예제에서는 SQL Server 캐시 종속성을 만들고 컨트롤의 SqlCacheDependencyObjectDataSource 속성을 설정하는 방법을 보여 줍니다. 이 예제에서는 데이터베이스가 120초마다 폴링됩니다. 이 시간 동안 Northwind Traders Employees 테이블의 데이터가 변경되면 컨트롤에 의해 ObjectDataSource 캐시되고 컨트롤에 GridView 의해 표시되는 모든 데이터가 만료되고 페이지에 대한 다음 요청에서 새 데이터 집합이 검색됩니다.
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!--
The page uses an example configuration that includes
connection strings and a defined SqlCacheDependecy.
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyNorthwind"
connectionString="Data Source="localhost";Integrated Security="SSPI";Initial Catalog="Northwind""
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<cache>
<sqlCacheDependency enabled="true">
<databases>
<add
name="Northwind"
connectionStringName="MyNorthwind"
pollTime="120000" />
</databases>
</sqlCacheDependency>
</cache>
</system.web>
</configuration>
-->
<!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>ObjectDataSource - C# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
typename="Samples.AspNet.CS.EmployeeLogic"
selectmethod="GetAllEmployeesAsDataSet"
enablecaching="True"
cacheduration="300"
cacheexpirationpolicy="Absolute"
sqlcachedependency="Northwind:Employees" />
</form>
</body>
</html>
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<!--
The page uses an example configuration that includes
connection strings and a defined SqlCacheDependecy.
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyNorthwind"
connectionString="Data Source="localhost";Integrated Security="SSPI";Initial Catalog="Northwind""
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<cache>
<sqlCacheDependency enabled="true">
<databases>
<add
name="Northwind"
connectionStringName="MyNorthwind"
pollTime="120000" />
</databases>
</sqlCacheDependency>
</cache>
</system.web>
</configuration>
-->
<!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>ObjectDataSource - VB Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
typename="Samples.AspNet.VB.EmployeeLogic"
selectmethod="GetAllEmployeesAsDataSet"
enablecaching="True"
cacheduration="300"
cacheexpirationpolicy="Absolute"
sqlcachedependency="Northwind:Employees" />
</form>
</body>
</html>
다음 코드 예제에서는 컨트롤을 사용하여 캐싱 및 필터링을 사용하도록 개체를 DataSet 반환하는 래퍼 메서드를 구현하는 ObjectDataSource 방법을 보여 줍니다. 클래스의 EmployeeLogic 기본 구현에서 메서드는 GetAllEmployees 개체를 반환합니다 ArrayList . Web Forms 페이지에서 작업 ObjectDataSource 하도록 개체를 완전히 리팩터링하는 대신 데이터 집합 NorthwindEmployee 을 로 DataSet반환하는 래퍼 GetAllEmployeesAsDataSet 메서드가 추가됩니다.
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 one 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;
}
//
// To support basic filtering, the employees cannot
// be returned as an array of objects, rather as a
// DataSet of the raw data values.
public static DataSet GetAllEmployeesAsDataSet () {
ICollection employees = GetAllEmployees();
DataSet ds = new DataSet("Table");
// Create the schema of the DataTable.
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("FirstName", typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("LastName", typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("Title", typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("Courtesy", typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("Supervisor",typeof(Int32)); dt.Columns.Add(dc);
// Add rows to the DataTable.
IEnumerator emplEnum = employees.GetEnumerator();
DataRow row;
NorthwindEmployee ne;
while (emplEnum.MoveNext()) {
ne = emplEnum.Current as NorthwindEmployee;
row = dt.NewRow();
row["FirstName"] = ne.FirstName;
row["LastName"] = ne.LastName;
row["Title"] = ne.Title;
row["Courtesy"] = ne.Courtesy;
row["Supervisor"] = ne.Supervisor;
dt.Rows.Add(row);
}
// Add the complete DataTable to the DataSet.
ds.Tables.Add(dt);
return ds;
}
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."); }
}
}
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 one 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
' To support basic filtering, the employees cannot
' be returned as an array of objects, rather as a
' DataSet of the raw data values.
Public Shared Function GetAllEmployeesAsDataSet() As DataSet
Dim employees As ICollection = GetAllEmployees()
Dim ds As New DataSet("Table")
' Create the schema of the DataTable.
Dim dt As New DataTable()
Dim dc As DataColumn
dc = New DataColumn("FirstName", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("LastName", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("Title", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("Courtesy", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("Supervisor", GetType(Int32))
dt.Columns.Add(dc)
' Add rows to the DataTable.
Dim emplEnum As IEnumerator = employees.GetEnumerator()
Dim row As DataRow
Dim ne As NorthwindEmployee
While emplEnum.MoveNext()
ne = CType(emplEnum.Current, NorthwindEmployee)
row = dt.NewRow()
row("FirstName") = ne.FirstName
row("LastName") = ne.LastName
row("Title") = ne.Title
row("Courtesy") = ne.Courtesy
row("Supervisor") = ne.Supervisor
dt.Rows.Add(row)
End While
' Add the complete DataTable to the DataSet.
ds.Tables.Add(dt)
Return ds
End Function 'GetAllEmployeesAsDataSet
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
End Class
Public Class NorthwindEmployee
Public Sub New()
ID = DBNull.Value
aLastName = ""
aFirstName = ""
aTitle = ""
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
설명
컨트롤은 ObjectDataSource 데이터 캐시의 개체를 기반으로 SqlCacheDependency 하는 선택적 만료 정책을 지원합니다(데이터베이스 서버에 대해 서비스를 구성해야 함).
SQL Server는 캐시 무효화를 위한 폴링 및 알림의 두 가지 메커니즘을 지원합니다. 각 메커니즘에는 개체에 대한 다른 구문이 있습니다 SqlCacheDependency .
폴 ObjectDataSource 링만 지원합니다. 이 SqlCacheDependency 문자열은 메서드가 SqlDependency 실행되기 전에 생성자에 전달되는 DbCommand 개체를 Select 만드는 데 사용됩니다. 문자열은 SqlCacheDependency 지시문에서 사용하는 것과 동일한 형식에 @ Page 따라 데이터베이스와 테이블을 식별합니다. 여기서 문자열의 첫 번째 부분은 SQL Server 데이터베이스에 대한 연결 문자열이고 콜론 구분 기호와 마지막으로 데이터베이스 테이블의 이름(예: "connectionstring1:table1")입니다. 속성이 SqlCacheDependency 둘 이상의 테이블에 의존하는 경우 연결 문자열과 테이블 이름 쌍은 세미콜론(예 "connectionstring1:table1";connectionstring2:table2": )으로 구분됩니다.
알림을 지원하려면 속성 구현 SelectMethod 에서 캐시 논리를 작성하고 코드에서 개체의 생성을 SqlCacheDependency 처리해야 합니다.