从简单的SQL查询填充C#类

时间:2016-08-24 16:01:28

标签: c# sql oop webforms sql-server-2012

我正在创建一个页面,它将在我们的数据库中显示审计表的最新记录,我可以使用以下查询获取该记录。

select top 1 StartDateTime, EndDateTime, Status 
from Audit
order by StartDateTime desc

由于这个信息将在我的整个应用程序中多次使用,我想创建一个可以在行中读取并填充" stats"我可以从任何页面调用的对象。

我的班级目前看起来像

public class Stats
{
    public DateTime startDate() {

        string mySQL;
        mySQL = "select top 1 StartDateTime from Audit order by StartDateTime desc";

        string myConnectionString;
        myConnectionString = "databaseCS";

        SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[myConnectionString].ConnectionString);

        SqlCommand myCommand = new SqlCommand(mySQL, myConnection);

        using (myConnection)
        {
            myConnection.Open();
            DateTime startDate = Convert.ToDateTime(myCommand.ExecuteScalar());
            return startDate;
        }

    }
    public DateTime endDate() 
    {
        string mySQL;
        mySQL = "select top 1 EndDateTime from Audit order by StartDateTime desc";

        string myConnectionString;
        myConnectionString = "databaseCS";

        SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[myConnectionString].ConnectionString);

        SqlCommand myCommand = new SqlCommand(mySQL, myConnection);

        using (myConnection)
        {
            myConnection.Open();
            DateTime endDate = Convert.ToDateTime(myCommand.ExecuteScalar());
            return endDate;
        }
    }

    public string status() {

        string mySQL;
        mySQL = "select top 1 EndDateTime from Audit order by StartDateTime desc";

        string myConnectionString;
        myConnectionString = "databaseCS";

        SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[myConnectionString].ConnectionString);

        SqlCommand myCommand = new SqlCommand(mySQL, myConnection);

        using (myConnection)
        {
            myConnection.Open();
            string status = Convert.ToString(myCommand.ExecuteScalar());
            return status;
        }


    }

显示数据的页面通常会显示至少2个这些统计信息,因此我想避免多个数据库查询。

有没有办法可以更改我的代码来查询数据库一次?

非常感谢

2 个答案:

答案 0 :(得分:-1)

更强大的示例

  public class MvcApplication : System.Web.HttpApplication
    {
        //Internal reference to the cache wrapper object
        private static ICacheService _internalCacheObject;

        //Public mehtod used to inject a new caching service into the application.
        // This method is required to ensure full testability. 
        public void RegisterCacheService(ICacheService cacheService)
        {
            _internalCacheObject = cacheService;
        }

        //Use this property to access the underlying cache object from within
        // controller methods. Use this instead of native Cache object.
        public static ICacheService CacheService
        {
            get { return _internalCacheObject; }
        }
        protected void Application_Start()
        { 
            //Inject a global caching service
            RegisterCacheService(new AspNetCacheService());
            //Store some sample app-wide data
            CacheService["StartTime"] = DateTime.Now; 
            //Call the cache service 
            // var data = MyNameSpace.MvcApplication.CacheService[...];
        }

    }

接口

public interface ICacheService
    {
        Object Get(String key);
        void Set(String key, Object data);
        Object this[String key] { get; set; }
    }

public class AspNetCacheService : ICacheService
    {
        private readonly Cache _aspnetCache;
        public AspNetCacheService()
        {
            if (HttpContext.Current != null)
            {
                _aspnetCache = HttpContext.Current.Cache;
            }
        }
        public Object Get(String key)
        {
            return _aspnetCache[key];
        }
        public void Set(String key, Object data)
        {
            _aspnetCache[key] = data;
        }
        public object this[String name]
        {
            get { return _aspnetCache[name]; }
            set { _aspnetCache[name] = value; }
        }

    }

答案 1 :(得分:-2)

在Global.asax的Application_start()中,从查询中调用数据表或数据集,然后将其保存到会话

      protected void Application_Start()
      {
        string query = "your query";
         ///Typically you would have some sort of datalayer
        SqlConnection sqlConn = new SqlConnection(conSTR);
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand(query, sqlConn);

        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        sqlConn.Close();

        ///Create Stat object
        Stats stat = new Stats();
        stat.startDate = dt.Columns["startDate"];
       //etc
       Session["stats"] = stat;
}

然后在页面上

 protected void Page_Load(object sender, EventArgs e)
    {
     Stats stat = Session["stats"] as Stats;
      }