MVC cache: uses the data layer cache to invalidate the cache when it is added or modified.

Source: Internet
Author: User
Tags actionlink

In "MVC cache 01, use controller cache or data layer cache", you can set useful cache time in the data layer. However, this is not "intelligent". It is often expected to invalidate the cache and load new data when it is modified or created.

□Ideas

1. the cache is stored with a key value <string, object = "">. when creating the cache, The IDictionary <int, t> is used as the cache content storage, int is the primary key of T.

 

2. When the EF context is retained, the changes are retained to the database and the content in the cache is updated.

● First, find the entity in the context that is added or modified: var changeobjects
● Keep the changed data to the database: context. SaveChanges ()
● Cache content obtained based on the Cache key of IDictionary <int, t>: var cacheData = Cache. Get ("vehicles") as Dictionary <int, vehicle = "">;
● Finally traverse these changed entities and update the cache items: cacheData [vehicle. Id] = vehicle;

 

□Cache Interface

    public interface ICacheProvider
    {
        object Get(string key);
        void Set(string key, object data, int cacheTime);
        bool IsSet(string key);
        void Invalidate(string key);
    }

 

□Cache interface completed

MemoryCache. Default for the MemoryCache. Back Type of using System. Runtime. Caching is the cache feature of ObjectCache. Complete cache interface: Get cache items, set cache, determine whether to set cache, clear cache.

using System;
using System.Runtime.Caching;
 
namespace MvcApplication1.Cache
{
    public class DefaultCacheProvider : ICacheProvider
    {
        private ObjectCache Cache
        {
            get { return MemoryCache.Default; }
        }
        public object Get(string key)
        {
            return Cache[key];
        }
 
        public void Set(string key, object data, int cacheTime)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
            Cache.Add(new CacheItem(key, data), policy);
        }
 
        public bool IsSet(string key)
        {
            return (Cache[key] != null);
        }
 
        public void Invalidate(string key)
        {
            Cache.Remove(key);
        }
    }
}
 

 

□Model

    public partial class Vehicle
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

 

□For Vehicle's Repositoy interface:

using System.Collections.Generic;
using MvcApplication1.Models;
 
namespace MvcApplication1.Repository
{
    public interface IVehicleRepository
    {
        void ClearCache();
        IEnumerableGetVehicles();
        void Insert(Vehicle vehicle); 
        void Update(Vehicle vehicle);
        void SaveChanges();
    }
}
 

□The Repositoy interface of Vehicle is completed:

using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using MvcApplication1.Cache;
using MvcApplication1.Models;
namespace MvcApplication1.Repository
{
    public class VehicleRepository : IVehicleRepository
    {
        protected DemoEntities DataContext { get; private set; }
        public ICacheProvider Cache { get; set; }
 
        public VehicleRepository() : this(new DefaultCacheProvider())
        {
            
        }
 
        public VehicleRepository(ICacheProvider cacheProvider)
        {
            this.DataContext = new DemoEntities();
            this.Cache = cacheProvider;
        }
 
        public void ClearCache()
        {
            Cache.Invalidate("vehicles");
        }
 
        public System.Collections.Generic.IEnumerable GetVehicles()
        {
            var vehicles = Cache.Get("vehicles") as IDictionary<int, Vehicle>;
            if (vehicles == null)
            {
                vehicles = DataContext.Vehicle.ToDictionary(v => v.Id);
                if (vehicles.Any())
                {
                    Cache.Set("vehicles",vehicles,30);
                }
            }
            return vehicles.Values;
        }
 
        public void Update(Vehicle vehicle)
        {
            if (vehicle != null)
            {
                DataContext.Set().Attach(vehicle);
                DataContext.Entry(vehicle).State = EntityState.Modified;
            }
        }
 
        public void Insert(Vehicle vehicle)
        {
            DataContext.Set().Add(vehicle);
        }
 
        public void SaveChanges()
        {
// Obtain the Vehicle whose EntityState is added or modified in the context.
             var changeobjects = DataContext.ChangeTracker.Entries();
 
// Retain changes to the database
            DataContext.SaveChanges();
 
// Update the Vehicle in the cache
            var cacheData = Cache.Get("vehicles") as Dictionary<int, Vehicle>;
            if (cacheData != null)
            {
                foreach (var item in changeobjects)
                {
                    var vehicle = item.Entity as Vehicle;
                    cacheData[vehicle.Id] = vehicle;
                }
            }
        }
    }
}
 

 

In the reserved Cache. before Set ("vehicles", vehicles, 30), convert the data obtained from the context to IDictionary <int, t> type vehicles = DataContext. vehicle. toDictionary (v => v. id );

 

□Homecontroller

using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using MvcApplication1.Repository;
 
namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public IVehicleRepository Repository { get; set; }
 
        public HomeController(IVehicleRepository repository)
        {
            this.Repository = repository;
        }
 
        public HomeController() : this(new VehicleRepository())
        {
            
        }
        public ActionResult Index()
        {
            return View(Repository.GetVehicles());
        }
 
        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            Repository.ClearCache();
            return RedirectToAction("Index");
        }
 
        public ActionResult Edit(int id)
        {
            var vehicle = Repository.GetVehicles().Single(v => v.Id == id);
            return View(vehicle);
        }
 
        [HttpPost]
        public ActionResult Edit(Vehicle vehicle)
        {
            Repository.Update(vehicle);
            Repository.SaveChanges();
            return RedirectToAction("Index");
        }
 
        public ActionResult Create()
        {
            return View(new Vehicle());
        }
 
        [HttpPost]
        public ActionResult Create(Vehicle vehicle)
        {
            Repository.Insert(vehicle);
            Repository.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}
 

 

□Home/Index. cshtml

@model IEnumerable
 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
 
 
"0" cellspacing="0" border="0">
    
        
        
        
        
    
    @foreach (var vehicle in Model)
    {
        
            
            
            
            
        
    }
 
No. Vehicle Model Quotation  
@ Vehicle. Id. ToString () @ Vehicle. Name @ String. Format ("{0: c}", vehicle. Price)
@ Html. ActionLink ("modify", "Edit", new {id = vehicle. Id })
        
 
@using (Html.BeginForm())
{
    "Submit" value = "invalidates the cache and retrieves database data from the ground up" id = "InvalidButton" name = "InvalidButton"/>
}
 
 

 

@ Html. ActionLink ("Create", "Create ")
 

 

 

□Home/Create. cshtml

@ Model MvcApplication1.Models. Vehicle @ {ViewBag. Title = "Create"; Layout = "~ /Views/Shared/_ Layout. cshtml ";} Create @ using (Html. beginForm () {@ Html. validationSummary (true) Vehicleclass = "editor-label"> @ Html. labelFor (model => model. name) class = "editor-field"> @ Html. editorFor (model => model. name) @ Html. validationMessageFor (model => model. name) class = "editor-label"> @ Html. labelFor (model => model. price) class = "editor-field"> @ Html. editorFor (model => model. price) @ Html. validationMessageFor (model => model. price) 

Value = "Save"/>

} @ Section Scripts {@ Scripts. Render ("~ /Bundles/jqueryval ")}

 

□Achievements:

Before creation or modification:

 

Modify and update:

 

Creation:

 

After the modification is created successfully:

Original article: http://www.codesocang.com/jiaocheng/MVCjiaocheng/2014/0408/7057.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.