更新数据集时更新缓存

时间:2012-05-29 06:18:18

标签: c# asp.net caching

我有一个数据集,用于存储各自国家的所有大陆。我正在缓存数据表:

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);
 }

现在我希望如果数据表有任何变化,应该从数据库中获取新数据。我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

根据您的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