2011-09-15 25 views
3

我想添加SqlCacheDependency到我的應用程序。 所以我決定創建littel tesp項目並面對困難。 我使用MSSQL 2008.我創建新的數據庫與錶行,並添加了幾行。 我執行:SqlCacheDependency不起作用

ALTER DATABASE ForTest SET ENABLE_BROKER 

在managmeng工作室。

ASPX頁面:

public partial class WebForm1 : System.Web.UI.Page 
    { 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
     if (Cache["Lines"] == null) 
     { 
     string connectionString = 
      WebConfigurationManager.ConnectionStrings["ForTest"].ConnectionString; 
     SqlConnection con = new SqlConnection(connectionString); 
     string query = "SELECT dbo.Lines.Id, dbo.Lines.Value FROM dbo.Lines"; 
     SqlCommand cmd = new SqlCommand(query, con); 
     SqlDataAdapter adapter = new SqlDataAdapter(cmd); 

     DataSet ds = new DataSet(); 
     adapter.Fill(ds, "Lines"); 

     SqlCacheDependency empDependency = new SqlCacheDependency(cmd); 
     Cache.Insert("Lines", ds, empDependency); 
     } 
     } 
    } 

    protected void btnResult_OnClick(object sender, EventArgs e) 
    { 
     var result = Cache["Lines"]; 
    } 
} 

我運行這個頁面,並添加行緩存,然後我在同治工作室添加行,當我點擊按鈕,我希望 高速緩存將被改變,但緩存仍舊。 我無法找到我做什麼錯:(你能不能給我一些暗示我該如何解決這個問題

感謝

更新: 我僞造者說,在global.aspx我運行:

SqlDependency.Start(
    WebConfigurationManager.ConnectionStrings["ForTest"].ConnectionString 
); 

回答

7

我也有類似的問題,這篇文章:Troubleshooting SqlCacheDependency in SQL Server 2008 and SQL Server 2005幫了我很多,然後

幾句話:在DATABSE是從備份中恢復,並創建該數據庫原始的Windows用戶沒有升onger可用。因此,我將數據庫所有權更改爲有效的登錄名,類似於:

ALTER AUTHORIZATION ON DATABASE::[my_perfect_database_name] TO [sa]; 

它現在就像一個魅力。

我是如何找到問題的根源的?我運行查詢SELECT * FROM sys.transmission_queue,發現下一個數據在transmission_status列:

An exception occurred while enqueueing a message in the target queue. Error: 15517, State: 1. Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission.

這個消息給了我一鍵解決問題。

0

代碼有錯誤;

sqldependency的定義應放在執行命令之前,否則它不會訂閱您的sqlcommand,那麼當您的命令的結果集更改時,它不會得到通知。

SqlCacheDependency empDependency = new SqlCacheDependency(cmd); 

DataSet ds = new DataSet(); 
adapter.Fill(ds, "Lines"); 
0

我還以爲我有一個問題,SqlCacheDependency在表被更改後沒有被清除。

原來,這是因爲我的測試。我只是通過管理工作室編輯SQL表中的行,並期望它通知並清除緩存。事實並非如此!如果您正在編輯表格,則還必須重新執行select sql以啓動清除緩存。