2013-10-04 23 views
1

在我的控制器我有一個方法是創建一個模型來容納來自數據庫的一些信息,有沒有辦法在方法內創建一些邏輯來檢查模型已經有數據在裏面了?這個SelectCompanyFromDropdown()每次用戶導航到另一個頁面時調用,但爲了減少我想檢查的數據庫調用。我想知道如果一個全局變量會做的伎倆,但我知道你可能會陷入調試全局。ASP.NET可以PartialViewResult檢查模型的狀態

pseudo: 
if(Model != null) 
Run Method 
return PartialView(new model) 
Else 
return PartialView(existing model) 

控制器的方法: 公共PartialViewResult SelectCompanyFromDropdown() {

  var coid = Lt.GetThisUsersCoId(); 
      var model = new CompanyViewModel(); 
      using (var dc = new CompanyViewModelDbContext()) 
      { 
       var content = 
        (from cr in db.CompanyRelationship 
        //This is grabbing all related companies to the logged in user 
        join c in db.Companies on cr.CoId equals c.CoId 
        where cr.PartnerCoId == coid 

        select new 
        { 
         cr.CoId, 
         c.CompanyName 
        }).Distinct().ToDictionary(cr => cr.CoId, c => c.CompanyName); 

       model.Companies = content; 

      } 
      return PartialView(model); 
     } 

這是發送所述模型的視圖下來創建的下降,然而,我想只參考現有的每個模型用戶更改頁面的時間。

+1

首先想到的是檢查一個必填字段,必須在任何情況下填寫。因此,如果Model.mandatoryField!= null,那麼做... – RealityDysfunction

+0

我實際上只是繼續並緩存數據,然後對緩存的對象進行檢查。 –

回答

1

如果數據庫調用的結果不會經常更改,則可以對其進行緩存。因此,通過編寫將執行此任務的方法開始:

private IDictionary<int, string> GetCompanies(int coid) 
{ 
    var result = MemoryCache.Default[coid.ToString()] as IDictionary<int, string>; 
    if (result != null) 
    { 
     // we already have cached results => no need to perform expensive database calls 
     // we can return directly the cached results; 
     return result; 
    } 

    // there's nothing in the cache => we need to make the DB call 
    // and cache the results for subsequent use 
    using (var dc = new CompanyViewModelDbContext()) 
    { 
     result = 
      (from cr in db.CompanyRelationship 
      //This is grabbing all related companies to the logged in user 
      join c in db.Companies on cr.CoId equals c.CoId 
      where cr.PartnerCoId == coid 
      select new 
      { 
       cr.CoId, 
       c.CompanyName 
      }).Distinct().ToDictionary(cr => cr.CoId, c => c.CompanyName); 
    } 

    var policy = new CacheItemPolicy 
    { 
     // Cache the results of the Db query for 24 hours 
     AbsoluteExpiration = DateTimeOffset.Now.AddHours(24), 
     Priority = CacheItemPriority.NotRemovable, 
    }; 

    MemoryCache.Default.Set(coid.ToString(), result, policy); 

    return result; 
} 

,現在所有剩下的在你的控制器動作是調用此方法來填充你的視圖模型:

var model = new CompanyViewModel(); 
var coid = Lt.GetThisUsersCoId(); 
model.Companies = GetCompanies(coid); 
return PartialView(model); 

而且你似乎對視圖模型有一些誤解。您的EF上下文似乎被稱爲CompanyViewModelDbContext。視圖模型是專門爲滿足視圖邏輯要求而設計的類。你的數據層(這是EF扮演的角色)應該完全不瞭解這種視圖邏輯。您的域模型不應與您的視圖模型綁定。

+0

那麼你說的是視圖模型應該只保存傳遞給視圖的信息?沒有數據庫邏輯?這是我最終實現的。 –