MvcSiteMapProvider 允许解决缓存依赖关系的动态站点地图。
您可以通过创建一个实现IDynamicNodeProvider
. 下面是一个基于数据库查询生成动态节点的示例,并且还设置了对同一查询的缓存依赖关系。
public class ProductNodesProvider : IDynamicNodeProvider
{
static readonly string AllProductsQuery =
"SELECT Id, Title, Category FROM dbo.Product;";
string connectionString =
ConfigurationManager.ConnectionStrings ["db"].ConnectionString;
/// Create DynamicNode's out of all Products in our database
public System.Collections.Generic.IEnumerable<DynamicNode> GetDynamicNodeCollection()
{
var returnValue = new List<DynamicNode> ();
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand command = new SqlCommand (AllProductsQuery, connection);
connection.Open ();
SqlDataReader reader = command.ExecuteReader ();
try {
while (reader.Read()) {
DynamicNode node = new DynamicNode ();
node.Title = reader [1];
node.ParentKey = "Category_" + reader [2];
node.RouteValues.Add ("productid", reader [0]);
returnValue.Add (node);
}
} finally {
reader.Close ();
}
}
return returnValue;
}
/// Create CacheDependancy on SQL
public CacheDescription GetCacheDescription ()
{
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand command = new SqlCommand (AllProductsQuery, connection);
SqlCacheDependency dependancy = new SqlCacheDependency (command);
return new CacheDescription ("ProductNodesProvider")
{
Dependencies = dependancy
};
}
}
}
虽然这一切都非常漂亮 - 当您的客户更改数据库中的产品时应该使缓存无效 - 整体SqlCacheDependancy
可能很棘手并且依赖于 SQL Server 版本。
CacheDependacy
如果您使用缓存来存储您的产品,您可以使用自定义选项。