MemoryCache没有添加

时间:2013-05-31 10:05:06

标签: sqldependency memorycache

我已经按照http://www.codeproject.com/Articles/167282/NET-4-0-MemoryCache-with-SqlChangeMonitor

上的示例实现了一个memorycache

我遇到问题,根本没有添加缓存。

我的代码:

using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Caching;

namespace  ClassLibrary{
    public  partial class TRANSLATION {

        public static string GetTranslationString(int id)
        {

            string trans = TRANSLATION.cached.Where(x => x.id == id).Select(x => x.Value).FirstOrDefault();

            if (trans == null)
            {
                return "";
            }
            else {
                return trans;
            }
        }

        public static List<TRANSLATION> cached()
        {
            List<TRANSLATION> lstTRANSLATION;

            if (MemoryCache.Default["TRANSLATION"] == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();

                SqlDependency.Start(cacher.sqlConn());

                using (SqlConnection conn = new SqlConnection(cacher.sqlConn()))
                {
                    using (SqlCommand command = new SqlCommand("SELECT [ID],[Value] FROM [TRANSLATION]", conn))
                    {
                        command.Notification = null;
                        SqlDependency dep = new SqlDependency();
                        dep.AddCommandDependency(command);
                        conn.Open();

                        SqlDataReader sqlReader = command.ExecuteReader();

                        lstTRANSLATION = new List<TRANSLATION>();
                        while (sqlReader.Read())
                        {
                            TRANSLATION trans = new TRANSLATION();
                            trans.ID = sqlReader.GetInt32(0);
                            trans.Value = sqlReader.GetString(1);
                            lstTRANSLATION.Add(trans);
                        }

                        SqlChangeMonitor monitor = new SqlChangeMonitor(dep);
                        policy.ChangeMonitors.Add(monitor);
                    }
                }

                MemoryCache.Default.Add("TRANSLATION", lstTRANSLATION, policy);
            }
            else
            {
                lstTRANSLATION = (List<TRANSLATION>)MemoryCache.Default.Get("TRANSLATION");
            }

            return lstTRANSLATION;
        }
    }
}

当我单步执行代码时,它找不到缓存,即使是.add()之后的行,我也找不到缓存。

当我添加以下代码时:

MemoryCache.Default.Add("test", "test", DateTime.Now.AddMinutes(5));

我可以在缓存中找到此密钥。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

using (SqlCommand command = new SqlCommand("SELECT [ID],[Value] FROM dbo.[TRANSLATION]", conn))

添加dbo.就可以了。