-1
我有一個保存功能和刷新功能。保存調用刷新功能。 保存需要4'756ms,刷新需要4'187ms - >保存不刷新需要569ms。 在刷新功能中,它將重新加載數據庫中的數據。 我怎樣才能保存我的數據本地,但保存到數據庫的更改,以便我有多次不加載數據庫中的數據?C#如何保持數據本地,而不是從數據庫中加載數據多次?
我使用實體框架5並使用存儲庫。
謝謝。
我有一個保存功能和刷新功能。保存調用刷新功能。 保存需要4'756ms,刷新需要4'187ms - >保存不刷新需要569ms。 在刷新功能中,它將重新加載數據庫中的數據。 我怎樣才能保存我的數據本地,但保存到數據庫的更改,以便我有多次不加載數據庫中的數據?C#如何保持數據本地,而不是從數據庫中加載數據多次?
我使用實體框架5並使用存儲庫。
謝謝。
您可以使用緩存像HttpContext.Current.Cache:
internal static class Cache<T>
{
public static void Save(IList<T> list, int insertAt, string cacheKey)
{
// Cache key per Session
cacheKey = HttpContext.Current.Session.SessionID + "~" + cacheKey;
if (list != null && list.Count > 0)
{
// if list is already there, insert items in list.
IList<T> cachedList = HttpContext.Current.Cache[cacheKey] as IList<T>;
if (cachedList != null)
{
// remove list from cache.
HttpContext.Current.Cache.Remove(cacheKey);
// insert items at position.
if (insertAt < 0)
{
insertAt = cachedList.Count;
}
foreach (T item in list)
{
cachedList.Insert(insertAt, item);
insertAt++;
}
}
else
{
// check that list is no array, because that cannot be removed.
cachedList = list.GetType().IsArray ? new List<T>(list) : list;
}
// save list in cache for 30 seconds.
HttpContext.Current.Cache.Insert(
cacheKey
, cachedList
, null
, DateTime.Now.AddSeconds(30)
, Cache.NoSlidingExpiration
);
}
}
public static void Save(IList<T> list, string cacheKey)
{
Save(list, -1, cacheKey);
}
public static void Save(IList<T> list, int insertAt)
{
Save(list, insertAt, typeof(T).Name);
}
public static int Remove(T item, string cacheKey)
{
// index of removed item.
int removedIndex = -1;
// cache key per Session
cacheKey = HttpContext.Current.Session.SessionID + "~" + cacheKey;
if (item != null)
{
// remove from cache.
IList<T> cachedList = HttpContext.Current.Cache[cacheKey] as IList<T>;
if (cachedList != null)
{
// remove list from cache.
HttpContext.Current.Cache.Remove(cacheKey);
// remove item from cached list..
removedIndex = cachedList.IndexOf(item);
cachedList.Remove(item);
// insert list for 30 sec.
HttpContext.Current.Cache.Insert(
cacheKey
, cachedList
, null
, DateTime.Now.AddSeconds(30)
, Cache.NoSlidingExpiration
);
}
}
return removedIndex;
}
public static int Remove(T item)
{
return Remove(item, typeof(T).Name);
}
public static void Clear(string cacheKey)
{
// cache Key per Session
cacheKey = HttpContext.Current.Session.SessionID + "~" + cacheKey;
HttpContext.Current.Cache.Remove(cacheKey);
}
public static void Clear()
{
Clear(typeof(T).Name);
}
}
請參閱緩存@ http://blogs.msdn.com/b/alexj/archive/2009/04/22 /tip-14-caching-entity-framework-reference-data.aspx http://www.codeproject.com/Articles/435142/Entity-Framework-Second-Level-Caching-with-DbConte – 2014-10-06 08:24:47
謝謝!緩存是我需要的:) – BlueSalamander 2014-10-06 13:26:45