SqlCacheDependency 클래스

정의

ASP.NET 애플리케이션의 Cache 개체에 저장된 항목과 특정 SQL Server 데이터베이스 테이블 또는 SQL Server 2005 쿼리 결과 간에 관계를 설정합니다. 이 클래스는 상속할 수 없습니다.

public ref class SqlCacheDependency sealed : System::Web::Caching::CacheDependency
public sealed class SqlCacheDependency : System.Web.Caching.CacheDependency
type SqlCacheDependency = class
    inherit CacheDependency
Public NotInheritable Class SqlCacheDependency
Inherits CacheDependency
상속
SqlCacheDependency

예제

다음 코드 예제에서는 및 GridView 컨트롤을 사용하여 SqlDataSource 데이터베이스 테이블을 표시합니다. 페이지가 로드되면 페이지에서 개체를 만들려고 SqlCacheDependency 시도합니다. 개체를 SqlCacheDependency 만든 후 페이지에서 개체에 대한 종속성이 SqlCacheDependency 있는 항목을 Cache 추가합니다. 여기에 표시된 것과 유사한 예외 처리를 사용해야 합니다.

<%@ Page Language="C#" Debug="true" %>
<%@ import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
// <snippet2>
    public void Page_Load(object Src, EventArgs E) 
    { 
        // Declare the SqlCacheDependency instance, SqlDep. 
        SqlCacheDependency SqlDep = null; 
        
        // Check the Cache for the SqlSource key. 
        // If it isn't there, create it with a dependency 
        // on a SQL Server table using the SqlCacheDependency class. 
        if (Cache["SqlSource"] == null) { 
            
            // Because of possible exceptions thrown when this 
            // code runs, use Try...Catch...Finally syntax. 
            try { 
                // Instantiate SqlDep using the SqlCacheDependency constructor. 
                SqlDep = new SqlCacheDependency("Northwind", "Categories"); 
            } 
            
            // Handle the DatabaseNotEnabledForNotificationException with 
            // a call to the SqlCacheDependencyAdmin.EnableNotifications method. 
            catch (DatabaseNotEnabledForNotificationException exDBDis) { 
                try { 
                    SqlCacheDependencyAdmin.EnableNotifications("Northwind"); 
                } 
                
                // If the database does not have permissions set for creating tables, 
                // the UnauthorizedAccessException is thrown. Handle it by redirecting 
                // to an error page. 
                catch (UnauthorizedAccessException exPerm) { 
                    Response.Redirect(".\\ErrorPage.htm"); 
                } 
            } 
            
            // Handle the TableNotEnabledForNotificationException with 
            // a call to the SqlCacheDependencyAdmin.EnableTableForNotifications method. 
            catch (TableNotEnabledForNotificationException exTabDis) { 
                try { 
                    SqlCacheDependencyAdmin.EnableTableForNotifications("Northwind", "Categories"); 
                } 
                
                // If a SqlException is thrown, redirect to an error page. 
                catch (SqlException exc) { 
                    Response.Redirect(".\\ErrorPage.htm"); 
                } 
            } 
            
            // If all the other code is successful, add MySource to the Cache 
            // with a dependency on SqlDep. If the Categories table changes, 
            // MySource will be removed from the Cache. Then generate a message 
            // that the data is newly created and added to the cache. 
            finally { 
                Cache.Insert("SqlSource", Source1, SqlDep); 
                CacheMsg.Text = "The data object was created explicitly."; 
                
            } 
        } 
        
        else { 
            CacheMsg.Text = "The data was retrieved from the Cache."; 
        } 
    } 
// </snippet2>
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <p>
        </p>
        <p>
            <asp:SqlDataSource id="Source1" runat="server" SelectCommand="SELECT * FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName]=@CategoryName,[Description]=@Description,[Picture]=@Picture WHERE [CategoryID]=@CategoryID" ConnectionString="<%$ ConnectionStrings:Northwind %>"></asp:SqlDataSource>
            <asp:GridView id="GridView1" runat="server" DataKeyNames="CategoryID" AllowSorting="True" AllowPaging="True" DataSourceID="Source1"></asp:GridView>
        </p>
        <p>
        </p>
        <p>
            <asp:Label id="CacheMsg" runat="server" AssociatedControlID="GridView1"></asp:Label>
        </p>
   </form>
</body>
</html>
<%@ Page Language="VB" Debug="True" %>
<%@ import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
' <snippet2>
    Sub Page_Load(Src As Object, E As EventArgs)
       ' Declare the SqlCacheDependency instance, SqlDep.
       Dim SqlDep As SqlCacheDependency

       ' Check the Cache for the SqlSource key.
       ' If it isn't there, create it with a dependency
       ' on a SQL Server table using the SqlCacheDependency class.
       If Cache("SqlSource") Is Nothing

          ' Because of possible exceptions thrown when this
          ' code runs, use Try...Catch...Finally syntax.
          Try
             ' Instantiate SqlDep using the SqlCacheDependency constructor.
             SqlDep = New SqlCacheDependency("Northwind", "Categories")

          ' Handle the DatabaseNotEnabledForNotificationException with
          ' a call to the SqlCacheDependencyAdmin.EnableNotifications method.
          Catch exDBDis As DatabaseNotEnabledForNotificationException
             Try
                SqlCacheDependencyAdmin.EnableNotifications("Northwind")

             ' If the database does not have permissions set for creating tables,
             ' the UnauthorizedAccessException is thrown. Handle it by redirecting
             ' to an error page.
             Catch exPerm As UnauthorizedAccessException
                 Response.Redirect(".\ErrorPage.htm")
             End Try

          ' Handle the TableNotEnabledForNotificationException with
                ' a call to the SqlCacheDependencyAdmin.EnableTableForNotifications method.
          Catch exTabDis As TableNotEnabledForNotificationException
             Try
                SqlCacheDependencyAdmin.EnableTableForNotifications( _
                 "Northwind", "Categories")

             ' If a SqlException is thrown, redirect to an error page.
             Catch exc As SqlException
                 Response.Redirect(".\ErrorPage.htm")
             End Try

          ' If all the other code is successful, add MySource to the Cache
          ' with a dependency on SqlDep. If the Categories table changes,
          ' MySource will be removed from the Cache. Then generate a message
                ' that the data is newly created and added to the cache.
          Finally
             Cache.Insert("SqlSource", Source1, SqlDep)
                CacheMsg.Text = "The data object was created explicitly."

          End Try

        Else
           CacheMsg.Text = "The data was retrieved from the Cache."
        End If
    End Sub
' </snippet2>

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <p>
        </p>
        <p>
            <asp:SqlDataSource id="Source1" runat="server" SelectCommand="SELECT * FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName]=@CategoryName,[Description]=@Description,[Picture]=@Picture WHERE [CategoryID]=@CategoryID" ConnectionString="<%$ ConnectionStrings:Northwind %>"></asp:SqlDataSource>
            <asp:GridView id="GridView1" runat="server" DataKeyNames="CategoryID" AllowSorting="True" AllowPaging="True" DataSourceID="Source1"></asp:GridView>
        </p>
        <p>
        </p>
        <p>
            <asp:Label id="CacheMsg" runat="server" AssociatedControlID="GridView1"></asp:Label>
        </p>
   </form>
</body>
</html>

설명

지원되는 모든 버전의 SQL Server(Microsoft SQL Server 7.0, Microsoft SQL Server 2000 및 SQL Server 2005)에서 SqlCacheDependency 클래스는 특정 SQL Server 데이터베이스 테이블을 모니터링합니다. 테이블이 변경되면 테이블과 연결된 항목이 제거 Cache되고 새 버전의 항목이 추가 Cache됩니다.

SqlCacheDependency 클래스는 SQL Server 2005 데이터베이스를 사용할 때 System.Data.SqlClient.SqlDependency 클래스와의 통합도 지원합니다. SQL Server 2005의 쿼리 알림 메커니즘은 SQL 쿼리의 결과를 무효화하는 데이터의 변경 내용을 검색하고 System.Web.Caching.Cache SQL 쿼리와 연결된 캐시된 항목을 제거합니다.

SqlCacheDependency 클래스를 사용하여 SQL Server 2005를 사용할 때 SQL Server 데이터베이스 테이블 또는 SQL 쿼리에 종속된 애플리케이션의 Cache 항목을 추가할 수 있습니다. @ OutputCache 지시문과 함께 이 클래스를 사용하여 출력 캐시 페이지 또는 SQL Server 데이터베이스 테이블에 종속된 사용자 컨트롤을 만들 수도 있습니다. 마지막으로 SqlCacheDependency 클래스를 @ OutputCache 페이지 지시문과 함께 사용하여 SQL Server 2005를 사용할 때 SQL 쿼리의 결과에 따라 출력 캐시된 페이지를 만들 수 있습니다. SQL Server 2005를 사용하는 쿼리 알림은 사용자 컨트롤에 대한 @ OutputCache 지시문에서 지원되지 않습니다.

Note

테이블 기반 알림을 사용할 때 이 클래스가 올바르게 작동하려면 데이터베이스와 종속성을 설정하려는 모든 테이블에 알림이 활성화되어 있어야 합니다. 클래스의 SqlCacheDependencyAdmin 메서드를 호출하거나 명령줄 도구를 사용하여 aspnet_regsql.exe 알림을 사용하도록 설정할 수 있습니다. 또한 애플리케이션의 Web.config 파일에 적절한 구성 설정을 포함해야 합니다.

SQL Server 2005 쿼리 알림과 함께 SqlCacheDependency 개체를 사용하면 명시적 구성이 필요하지 않습니다. 쿼리 알림을 사용할 때 허용되는 Transact-SQL 쿼리 유형에 대한 제한 사항에 대한 자세한 내용은 SQL Server 설명서를 참조하세요.

다음 예제에서는 SQL Server 데이터베이스 테이블에 대한 테이블 기반 종속성을 사용하도록 설정하는 ASP.NET Web.config 파일을 보여 줍니다.

<configuration>
  <connectionStrings>
    <add name="Northwind" connectionString="Data Source=(local); Initial Catalog=northwind; Integrated Security=true"; providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <caching>
      <sqlCacheDependency enabled = "true" pollTime = "60000" >
        <databases>
          <add name="northwind"
            connectionStringName="Northwind"
            pollTime="9000000"
            />
        </databases>
      </sqlCacheDependency>
    </caching>
  </system.web>
</configuration>

생성자

Name Description
SqlCacheDependency(SqlCommand)

제공된 SqlCommand 클래스를 사용하여 캐시 키 종속성을 만들어 클래스의 SqlCacheDependency 새 인스턴스를 초기화합니다.

SqlCacheDependency(String, String)

제공된 매개 변수를 사용하여 캐시 키 종속성을 만들어 클래스의 SqlCacheDependency 새 인스턴스를 초기화합니다.

속성

Name Description
HasChanged

개체가 변경되었는지 여부를 CacheDependency 나타내는 값을 가져옵니다.

(다음에서 상속됨 CacheDependency)
UtcLastModified

종속성이 마지막으로 변경된 시간을 가져옵니다.

(다음에서 상속됨 CacheDependency)

메서드

Name Description
CreateOutputCacheDependency(String)

ASP.NET 애플리케이션의 OutputCache 개체에 저장된 항목과 SQL Server 데이터베이스 테이블 간에 종속성 관계를 만듭니다.

DependencyDispose()

클래스에서 사용하는 CacheDependency 리소스와 에서 파생 CacheDependency되는 모든 클래스를 해제합니다.

(다음에서 상속됨 CacheDependency)
Dispose()

개체에서 사용하는 리소스를 CacheDependency 해제합니다.

(다음에서 상속됨 CacheDependency)
Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.

(다음에서 상속됨 Object)
FinishInit()

개체의 CacheDependency 초기화를 완료합니다.

(다음에서 상속됨 CacheDependency)
GetFileDependencies()

파일 종속성을 가져옵니다.

(다음에서 상속됨 CacheDependency)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type 가져옵니다.

(다음에서 상속됨 Object)
GetUniqueID()

개체의 고유 식별자를 검색 SqlCacheDependency 합니다.

ItemRemoved()

모니터링되는 캐시 항목이 제거될 때 호출됩니다.

(다음에서 상속됨 CacheDependency)
KeepDependenciesAlive()

이 항목에 의존하는 모든 캐시 항목의 마지막 액세스 시간을 업데이트합니다.

(다음에서 상속됨 CacheDependency)
MemberwiseClone()

현재 Object단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
NotifyDependencyChanged(Object, EventArgs)

파생 CacheDependency 클래스가 나타내는 종속성이 변경되었음을 기본 CacheDependency 개체에 알릴 수 있습니다.

(다음에서 상속됨 CacheDependency)
SetCacheDependencyChanged(Action<Object,EventArgs>)

이 종속성의 변경 내용에 대해 이해 당사자에게 알리는 작업을 처리하는 Action 메서드를 추가합니다.

(다음에서 상속됨 CacheDependency)
SetUtcLastModified(DateTime)

종속성이 마지막으로 변경된 시간을 표시합니다.

(다음에서 상속됨 CacheDependency)
TakeOwnership()

첫 번째 사용자가 이 종속성의 배타적 소유권을 선언할 수 있도록 허용합니다.

(다음에서 상속됨 CacheDependency)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보