是否可以将数据临时存储在C#.Net应用程序中,以减少从SQL Server调用数据的需求?

JK.*_*JK. 3 c# sql sql-server ado.net

我创建了一个C#.net应用程序,该应用程序使用SQL Server 2008数据库表中的日期。有没有一种方法可以我临时存储数据,以便我的程序不必重复对同一组信息进行服务器调用?我知道如何提取所需的信息并创建一个临时数据集,但是,只有特定的方法或类才能访问它,然后消失。在程序关闭之前,我需要通用的结果。

这是到目前为止,我不确定下一步该怎么做:

SqlConnection ReportConnect = new SqlConnection(ConnectionString);
String reportQuery = @"SELECT DISTINCT DATE FROM dbo.myTable ORDER BY DATE DESC";

ReportConnect.Open();

SqlCommand cmd = ReportConnect.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = ReportConnect;
cmd.CommandText = reportQuery.ToString();

SqlDataReader rdr = cmd.ExecuteReader();

while(rdr.Read()) {
   //I can access the results here 
}

//how do I add this data for the life of the program instance to my current
//dataset.  Let's say the dataset is named "activeDataset"
Run Code Online (Sandbox Code Playgroud)

Ric*_*lay 5

如果要使用键/值对缓存,建议您使用HttpRuntime.Cache(在ASP.NET应用程序外部可用),因为它已经为您完成了很多工作。

在最简单的实现中:

public IList<DateTime> GetUniqueDates()
{
    const string CacheKey = "RepositoryName.UniqueDates";

    Cache cache = HttpRuntime.Cache;

    List<DateTime> result = cache.Get[CacheKey] as List<DateTime>;

    if (result == null)
    {
        // If you're application has multithreaded access to data, you might want to 
        // put a double lock check in here

        using (SqlConnection reportConnect = new SqlConnection(ConnectionString))
        {
            // ...
            result = new List<DateTime>();

            while(reader.Read())
            {
                result.Add((DateTime)reader["Value"]);
            }
        }

        // You can specify various timeout options here
        cache.Insert(CacheKey, result);
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

话虽如此,为了凝聚起见,我通常使用IoC技巧在存储库前面创建一个缓存层。