2

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

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

现在我想如果数据表有任何变化,应该从数据库中获取新数据。我怎样才能做到这一点?

4

1 回答 1

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

一些背景可以在这里找到:在 ASP.NET 中使用 SqlCacheDependency 类进行缓存

于 2012-05-29T06:42:46.763 回答