Domanda

I have implemented a memorycache following the example on http://www.codeproject.com/Articles/167282/NET-4-0-MemoryCache-with-SqlChangeMonitor

I have a problem, the cache isn't added at all.

My code:

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

When I step through the code, it doesn't find the cache, even the line after .add(), I can't find the cache.

When I add the following code:

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

I can find this key in the cache.

What am I doing wrong?

È stato utile?

Soluzione

I found the solution:

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

Adding dbo. did the trick.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top