我有一个数据集,其中存储了所有大陆及其各自的国家/地区。我正在缓存数据表:
DataSet dset = new DataSet();
string cacheKey = "CoverageDataTable";
object cacheItem = Cache[cacheKey] as DataTable;
if (cacheItem == null)
{
dset = (DataSet)_obj.GetAllContinent();
cacheItem = dset.Tables[0];
Cache.Insert(cacheKey, cacheItem, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(5), CacheItemPriority.High, null);
}
现在我希望如果数据表中有任何更改,应该从数据库中获取新数据。我怎样才能做到这一点?
最佳答案
根据您的 SQL 数据库版本,您也许能够使用 SqlCacheDependency。
在 web.config 中非常简短
<caching>
<sqlCacheDependency pollTime="10000" enabled="true" >
<databases>
<add connectionStringName="ConnectionString" name="Coverage"/>
</databases>
</sqlCacheDependency>
</caching>
然后在代码中
private void BindData()
{
// if null then fetch from the database
if (Cache["CoverageDataTable"] == null)
{
// Create the cache dependency
SqlCacheDependency dep = new SqlCacheDependency("Coverage", CoverageDataTable");
string connectionString = ConfigurationManager.ConnectionStrings[
"ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT ColA, ColB, ColC " +
"FROM CoverageDataTable", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
// put in the cache object
Cache.Insert("CoverageDataTable", ds, dep);
}
gvCoverageDataTable.DataSource = Cache["CoverageDataTable"] as DataSet;
gvCoverageDataTable.DataBind();
}
一些背景可以在这里找到:Caching in ASP.NET with the SqlCacheDependency Class
关于c# - 数据集更新时更新缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10793997/