Cache應用

1.首先從數據庫中取數據,代碼如下:

private const string CacheAllProduct = "MyProduct";
        private const string ConnectionString = "";
        private const string StoredProcedureName_GetProduct = "GetAllProduct";
        private const string DataTableProductId = "ProductId";
        private const string DataTableProductName = "ProductName";
        private const string DataTableProductPrice = "ProductPrice";

        public static DataTable GetAllProduct(out SqlCacheDependency sqlCacheDependency)
        {
            DataTable dt = new DataTable(CacheAllProduct);

            using (SqlConnection sqlCon = new SqlConnection(ConnectionString))
            {
                SqlCommand sqlCmd = new SqlCommand(StoredProcedureName_GetProduct, sqlCon);
                sqlCacheDependency = new SqlCacheDependency(sqlCmd);
                sqlCmd.CommandType = CommandType.StoredProcedure;
                try
                {
                    sqlCon.Open();
                    SqlDataReader reader = sqlCmd.ExecuteReader();

                    dt.Load(reader);
                    reader.Close();
                }
                catch
                {
                    throw;
                }
            }

            return dt;
        }

2.下面是往Cache中塞值並且轉換成爲數據字典,如下:

在這裏強調一點,對於HttpRuntime.Cache.Insert(string key, object value, CacheDependency dependencies);的第三個參數官方的解釋是這樣的:

dependencies:
             The file or cache key dependencies for the inserted object. When any dependency
             changes, the object becomes invalid and is removed from the cache. If there
             are no dependencies, this parameter contains null.

也就是說對於Cache,它存在一個內部的機制如果SqlDependency發生變化就會清空Cache。

public static Dictionary<string, Product> Products
        {
            get
            {
                if (HttpRuntime.Cache[CacheAllProduct] == null)
                {
                    SqlCacheDependency sqlCacheDependency;
                    DataTable dt = GetAllProduct(out sqlCacheDependency);
                    HttpRuntime.Cache.Insert(CacheAllProduct, ConvertToProductsDictionary(dt), sqlCacheDependency);
                }

                return HttpRuntime.Cache[CacheAllProduct] as Dictionary<string, Product>;
            }
        }

 

3.下面是轉換的方法:

private static Dictionary<string, Product> ConvertToProductsDictionary(DataTable dataTable)
        {
            Dictionary<string, Product> productDictionary = new Dictionary<string, Product>();

            foreach (var item in ConvertToProductList(dataTable))
            {
                if (!productDictionary.ContainsValue(item))
                {
                    productDictionary.Add(item.ProductId.ToUpper().Trim(), item);
                }
            }

            return productDictionary;
        }

        private static List<Product> ConvertToProductList(DataTable dataTable)
        {
            List<Product> products = new List<Product>();
            foreach (DataRow row in dataTable.Rows)
            {
                products.Add(ConvertToProduct(row));
            }

            return products;
        }

        private static Product ConvertToProduct(DataRow row)
        {
            Product result = new Product()
            {
                ProductId = row[DataTableProductId].ToString(),
                ProductName = row[DataTableProductName].ToString(),
            };

            if (row[DataTableProductPrice] != DBNull.Value)
            {
                result.ProductPrice = Convert.ToDecimal(row[DataTableProductPrice]);
            }

            return result;
        }

    }


 

4.最後是數據庫對應的實體:

public class Product
    {
        public string ProductId { get; set; }

        public string ProductName { get; set; }

        public decimal ProductPrice { get; set; }
    }


 

5.由於SqlDependency只支持簡單的查詢語句,所以如果涉及多張表時候參考這裏:http://blog.csdn.net/cai15191466621/article/details/7493308
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章