2012-09-15 15 views
0

我正在使用asp.net Sqlmembership.GetAll()方法(分頁超載)。現在我想添加一個緩存層以緩存結果,但GetAll方法的輸出參數存在問題,該參數返回記錄的總數。當從緩存中檢索數據時,如何將值分配給totalRecords參數?使用緩存分配出參數totalRecords

回答

0

如果我的理解是正確的這個小流將幫助你實現你的目標

這是一個基本的流程:

  1. 當要訪問緩存的對象,要求它的緩存提供
  2. 如果對象不爲空,則轉換爲正確的類型並從緩存中返回對象(在本例中爲用戶列表)。端處理
  3. 如果對象是空值,則
    1. 檢索從其原始來源的對象(使用GetAll方法)
    2. 保存檢索的對象到緩存
    3. 返回所檢索的對象。結束進程

在任何情況下,我會建議您使用自定義域類工作的MembershipUser類而不是

這是一個基本的例子:

public IEnumerable<DomainUser> GetDomainUsers() 
    { 
     var context = HttpContext.Current; 
     var cache = context.Cache; 
     var domainUsers = cache["domainUsers"] as IEnumerable<DomainUser>; 

     if (domainUsers == null) 
     { 
      domainUsers = Membership.GetAllUsers().OfType<MembershipUser>().Select(x => new DomainUser 
       { 
        Email = x.Email, 
        Username = x.UserName 
       }); 

      cache.Insert(
       "domainUsers", // cache key 
       domainUsers, // object to cache 
       null, // dependencies 
       DateTime.Now.AddMinutes(30), // absoulute expiration 
       Cache.NoSlidingExpiration, // slading expiration 
       CacheItemPriority.High, // cache item priority 
       null // callback called when the cache item is removed 
      ); 

      context.Trace.Warn("Data retrieved from its original source"); 
     } 
     else 
     { 
      context.Trace.Warn("Data retrieved from cache"); 

     } 

     return domainUsers; 
    } 
+0

我有問題與接受分頁參數的GetAllUsers重載:GetAllUsers(int pageIndex,int pageSize,out int totalRecords)。我不知道如何爲數據來自緩存中的totalRecords參數賦值 –

+0

我明白了。但是你的目標是緩存來自數據庫的記錄,因此我認爲最好是緩存所有記錄,然後在內存中執行分頁。 **然而**,我建議你三思想你想完成什麼,如果你想緩存它可能是因爲查詢需要太長的時間來執行或者你的Web和數據服務器之間的延遲是不可接受的,如果這是這種情況,然後緩存整個對象並在內存中執行分頁。如果沒有,那麼緩存可能不會顯着改善您網站的性能 – Jupaol