using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Data.SqlClient;
using System.Configuration;

namespace BookDemo.QA
{
    public class ConfigCache : BaseCache<QAConfig>
    {
        public const string CACHE_KEY = "QAConfig";
        //设置缓存依赖参数
        System.Web.Caching.SqlCacheDependency sqlCacheDependency;

        public ConfigCache()
            : base(CACHE_KEY)
        {
            base._timeout = 30;
        }

        public override QAConfig Data
        {
            get
            {
                return base.Data;
            }
            set
            {
                //建立数据库同步更新委托
                UpdateWithBataBase updateWithDatabase = new UpdateWithBataBase(this.UpdateToDatabase);
                SetSqlCacheDependency();//设置数据库依赖参数
                base.SetData(value, base._timeout, sqlCacheDependency, updateWithDatabase);//设置缓存项
            }
        }

        public override QAConfig Update()
        {
            BookDemoEntities ctx = new BookDemoEntities();//创建Linq to Entities的对象上下文实例
            QAConfig config = (from c in ctx.QAConfig select c).FirstOrDefault();//查询全局配置信息
            SetSqlCacheDependency();//设置数据库依赖参数
            base.SetData(config, base._timeout, sqlCacheDependency, null);//设置缓存项
            return config;
        }
        /// <summary>
        /// 更新数据库
        /// 此方法可直接“拉动”数据库更新，而不使用数据库轮询
        /// </summary>
        /// <param name="obj"></param>
        public override void UpdateToDatabase(QAConfig obj)
        {
            BookDemoEntities ctx = new BookDemoEntities();//创建Linq to Entities的对象上下文实例
            QAConfig config = ctx.QAConfig.FirstOrDefault();//查询全局配置信息
            if (config != null)
            {
                //更新全局配置信息
                config.Solved = obj.Solved;
                config.Unsolve = obj.Unsolve;
                ctx.SaveChanges();//保存到数据库
            }
        }
        /// <summary>
        /// 设置数据库依赖参数
        /// </summary>
        private void SetSqlCacheDependency()
        {
            sqlCacheDependency = new System.Web.Caching.SqlCacheDependency(
                   "BookDemo",//对应Web.config中sqlCacheDependency\databases参数中的name
                   "QAConfig"//对应数据库表的名称
                   );
        }
    }
}
