I use the following code to cache, depending on the change in the People, Name table. However, in a row, if any other column, such as an address column, changes, the dependency also starts and clears the cache. (ASP.NET 4.0 with SQL Server 2008.)
public string GetTheVals() { string vals = HttpContext.Current.Cache["TheCacheKey__X"] as string; if (vals == null) { con = GetConnection(); SqlCommand cmd = new SqlCommand(@" SELECT Name FROM dbo.People ", con); con.Open(); SqlCacheDependency sqlDependency = new SqlCacheDependency(cmd); SqlDataReader rdr = null; StringBuilder builder = new StringBuilder(""); rdr = cmd.ExecuteReader(); while (rdr.Read()) { builder.Append(rdr[0].ToString()); } vals = builder.ToString(); HttpContext.Current.Cache.Insert("TheCacheKey__X", vals, sqlDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(20)); CloseConnection(con); } return vals; }
Why does it fire when the value of a column that is not in the command request has changed, although it is believed that it was run when the results changed?
You can also assign a delegate to the OnChange event, which will fire when the results are changed for the corresponding command.
http://msdn.microsoft.com/en-us/library/62xk7953.aspx
It is also necessary to explicitly specify the columns, so we understand that it will filter out the other columns of the table and will not work.
- So why do you need to explicitly specify column names?
- Is it just to let developers know what they are doing (for example, using internal joins) and avoid creating dependencies that can lead to the worst performance?
The projected columns in the SELECT statement must be explicitly specified , and the table names must be qualified with two-part names. notice that this means that all tables referenced in the application must be in the same database.
The statement may not use the asterisk (*) syntax or table_name syntax. * specify columns.
The operator must not contain subqueries, external joins, or self-joins.
http://msdn.microsoft.com/en-us/library/ms181122(v=sql.105).aspx