[英]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.