簡體   English   中英

何時從數據庫更新ViewModel [緩存ViewModel]

[英]When to Update the ViewModel from Database [Caching ViewModel]

好吧,我將嘗試使事情簡短明了。

如您所知,我有使用EntityFramework的數據庫,然后有通過數據庫初始化的數據庫模型類,然后有視圖模型,其中有每個html控件的字段,最后有控制器一個特定的ViewModel實例。

我的問題是,視圖模型是在控制器(任何操作)請求上創建一次的 ,其他時候我總是檢查它是否為空,如果它為空,那么我將重建視圖模型,以使用數據庫從數據庫中獲取數據模型類,這是對的事,對嗎? 這樣我就可以改善性能。 因為我正在重用視圖模型,而不是每次都沒有創建它...?

當管理員在Backoffice中更新某些字段時,就會出現問題。 我該如何克服? 我看到以下選項:

1)在控制器內部的ViewModel對象上設置生命周期(分鍾/小時)(一旦過期,我將其設置為null)。

2)我嘗試處理CTRL + F5組合鍵,並將控制器內部的ViewModel對象設置為null。

3)我向控制器的每個HTTP請求都重建ViewModel(這太糟糕了...)

4)我使用每個客戶端的Http會話,當后台更新一個字段時,我的ASP.NET WebApplication上的每個Http會話都會被觸發,並帶有一些將View Model對象設置為null的標志(我什至不知道這是否可能) ,但這似乎是最優雅的方法,對嗎?

這是我目前正在做的一個示例,但是在某些情況下,我可能需要重新創建ViewModel(因為更改了View字段的數據庫):

    [Authorize]
    public class HomeController : Controller
    {
        private IndexViewModel indexModel;

        [Authorize]
        public ActionResult Index(IndexViewModel model, string lang = "en")
        {
            indexModel = model;
            if (indexModel == null)
                indexModel = new IndexViewModel();

            indexModel.SelectedLanguage = lang;

            return View(indexModel);
        }

       //more actions..
}

期待聽到您的所有答復和反饋,這是一個主要針對性能和CPU時間優化的問題,我希望我的客戶在使用我的網站時獲得全新,干凈和快速的體驗。

謝謝!

編輯:問題與更多的信息進行了編輯。

默認情況下,將在每個請求上實例化ASP.NET MVC控制器。 這意味着您的indexModel變量在每個請求中始終為null 網絡是無狀態的,因此您幾乎沒有選擇來存儲請求之間的信息。

客戶端

  • 曲奇餅
  • 隱藏的領域

服務器端

  • 數據庫或其他存儲
  • 屆會
  • 快取

據我了解,您使用一些數據庫,只是想防止針對每個請求將查詢發送到數據庫,以實現更好的性能。 選項之一是使用System.Web.Caching.Cache對象。 然后,您可以編寫類似的內容。

public class HomeController : Controller
{
    [Authorize]
    public ActionResult Index(string lang = "en")
    {
        IndexViewModel indexViewModel;
        if (HttpContext.Cache["IndexViewModel"]!=null) 
        {
            indexViewModel = HttpContext.Cache["IndexViewModel"];
        }
        else 
        {
            // get your index view model from database by calling some service or repository
            indexViewModel = DatabaseService.GetIndexViewModelFromDatabase();
            // once we got the view model from a database we store it to cache and set it up so that it gets expired in 1 minute
            HttpContext.Cache.Insert("IndexViewModel", indexViewModel, null, DateTime.UtcNow.AddMinutes(1), Cache.NoSlidingExpiration);
        }

        indexViewModel.SelectedLanguage = lang;

        return View(indexModel);
    }

   [HttpPost]
   [Authorize(Roles="Backoffice")]
   public ActionResult ResetCache(string cacheKey)
   {
       if (HttpContext.Cache[cacheKey] != null)
           HttpContext.Cache.Remove(cacheKey);
   }
   //more actions..
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM