Use Azure Redis Cache With MVC And Entity Framework

Introduction

Azure Redis Cache is based on the popular open-source Redis cache. It is typically used as a cache to improve the performance and scalability of systems that rely heavily on backend data-stores. Performance is improved by temporarily copying frequently accessed data to fast storage located close to the application. With Redis cache, this fast storage is located in-memory with Redis Cache instead of being loaded from disk by a database.

Azure Redis Cache can also be used as an in-memory data structure store, distributed non-relational database, and message broker. Application performance is improved by taking advantage of the low-latency, high-throughput performance of the Redis engine.

Azure Redis Cache gives you access to a secure, dedicated Redis cache, managed by Microsoft, hosted within Azure, and accessible to any application within Azure.

This article shows you how to get started using Microsoft Azure Redis Cache with MVC.

Prerequisites

Create a cache

To create a cache, first, sign in to the Azure portal, and click Create a resource > Databases > Redis Cache.

Use Azure Redis Cache With MVC And Entity Framework

 

In New Redis Cache, configure the settings for your new cache.

Use Azure Redis Cache With MVC And Entity Framework

 

Once the new cache settings are configured, click Create.

It can take a few minutes for the cache to be created. To check the status, you can monitor the progress on the dashboard. After the cache has been created, your new cache has a Running status and is ready for use.

Use Azure Redis Cache With MVC And Entity Framework

Retrieve the hostname, ports, and access keys using the Azure Portal

When connecting to an Azure Redis Cache instance, cache clients need the hostname, ports, and a key for the cache. Some clients may refer to these items by slightly different names. You can retrieve this information in the Azure portal.

To retrieve the access keys using the Azure portal, browse to your cache and click Access keys.

Use Azure Redis Cache With MVC And Entity Framework

 

To retrieve hostname and ports, click Properties.

Use Azure Redis Cache With MVC And Entity Framework

Create MVC Project

Open Visual Studio > Visual C# > Web > ASP.NET Web Application (.NET Framework).

Use Azure Redis Cache With MVC And Entity Framework

 

Select Empty > select MVC > click OK

Use Azure Redis Cache With MVC And Entity Framework

Edit the web.config file and add the following contents in app settings,

  1. <add key="CacheConnection" value="<cache-name>.redis.cache.windows.net,abortConnect=false,ssl=true,password=<access-key>"/>  

Replace <cache-name> with your cache host name.

Replace <access-key> with the primary key for your cache.

In the Models folder, create a new class named Employee.

  1. [Serializable]  
  2.     public class Employee  
  3.     {  
  4.         public int Id { get; set; }  
  5.         public string Name { get; set; }  
  6.         public decimal Salary { get; set; }  
  7.   
  8.     }  

from NuGet, add Entity Framework Package.

Use Azure Redis Cache With MVC And Entity Framework

 

Create new class named EmployeeContext inherit from DbContext

  1. public class EmployeeContext:DbContext  
  2.  {  
  3.      public EmployeeContext():base("name=mycs")  
  4.      {  
  5.   
  6.      }  
  7.      public DbSet<Employee> Employees { get; set; }  
  8.  }  

Add connection string to web.config.

  1. <add name="mycs" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=EmployeeDB_1;Integrated Security=True;MultipleActiveResultSets=True"/>  

Create new class and rename to AzureCache, put the following code.

  1. public static class AzureCache  
  2.     {  
  3.         private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>  
  4.         {  
  5.             string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();  
  6.             return ConnectionMultiplexer.Connect(cacheConnection);  
  7.         });  
  8.   
  9.         public static ConnectionMultiplexer Connection  
  10.         {  
  11.             get  
  12.             {  
  13.                 return lazyConnection.Value;  
  14.             }  
  15.         }  
  16.   
  17.   
  18.         public static T Get<T>(string cacheKey)  
  19.         {  
  20.             return Deserialize<T>(Connection.GetDatabase().StringGet(cacheKey));  
  21.         }  
  22.   
  23.         public static object Get(string cacheKey)  
  24.         {  
  25.             return Deserialize<object>(Connection.GetDatabase().StringGet(cacheKey));  
  26.         }  
  27.   
  28.         public static void Set(string cacheKey, object cacheValue)  
  29.         {  
  30.             Connection.GetDatabase().StringSet(cacheKey, Serialize(cacheValue));  
  31.         }  
  32.   
  33.         private static byte[] Serialize(object obj)  
  34.         {  
  35.             if (obj == null)  
  36.             {  
  37.                 return null;  
  38.             }  
  39.             BinaryFormatter objBinaryFormatter = new BinaryFormatter();  
  40.             using (MemoryStream objMemoryStream = new MemoryStream())  
  41.             {  
  42.                 objBinaryFormatter.Serialize(objMemoryStream, obj);  
  43.                 byte[] objDataAsByte = objMemoryStream.ToArray();  
  44.                 return objDataAsByte;  
  45.             }  
  46.         }  
  47.   
  48.         private static T Deserialize<T>(byte[] bytes)  
  49.         {  
  50.             BinaryFormatter objBinaryFormatter = new BinaryFormatter();  
  51.             if (bytes == null)  
  52.                 return default(T);  
  53.   
  54.             using (MemoryStream objMemoryStream = new MemoryStream(bytes))  
  55.             {  
  56.                 T result = (T)objBinaryFormatter.Deserialize(objMemoryStream);  
  57.                 return result;  
  58.             }  
  59.         }  
  60.     }  

Add new controller to project > Select MVC 5 Controller with views, using Entity Framework

Use Azure Redis Cache With MVC And Entity Framework

 

Select the Model class, Data Context class and controller name

Use Azure Redis Cache With MVC And Entity Framework

 

In Controller Class add the following code as a global variable

  1. IDatabase cache = AzureCache.Connection.GetDatabase();  
  2. public class HomeController : Controller  
  3.     {  
  4.         IDatabase cache = AzureCache.Connection.GetDatabase();  
  5. …  
  6. }  

Update the index action code to the following code,

  1. var lstSampleObject = AzureCache.Get<List<Employee>>("lstEmps");  
  2.         if (lstSampleObject != null)  
  3.         {  
  4.             return View(lstSampleObject);  
  5.         }  
  6.         else  
  7.         {  
  8.             AzureCache.Set("lstEmps", db.Employees.ToList());  
  9.             return View(db.Employees.ToList());  
  10.         }  

Update the Create action code to the following code,

  1. [HttpPost]  
  2.    [ValidateAntiForgeryToken]  
  3.    public ActionResult Create([Bind(Include = "Id,Name,Salary")] Employee employee)  
  4.    {  
  5.        if (ModelState.IsValid)  
  6.        {  
  7.            db.Employees.Add(employee);  
  8.            db.SaveChanges();  
  9.             AzureCache.Set("lstEmps", db.Employees.ToList());  
  10.            return RedirectToAction("Index");  
  11.        }  
  12.   
  13.        return View(employee);  
  14.    }  

Update the Edit action code to the following code,

  1. [HttpPost]  
  2.         [ValidateAntiForgeryToken]  
  3.         public ActionResult Edit([Bind(Include = "Id,Name,Salary")] Employee employee)  
  4.         {  
  5.             if (ModelState.IsValid)  
  6.             {  
  7.                 db.Entry(employee).State = EntityState.Modified;  
  8.                 db.SaveChanges();  
  9.   
  10.                 AzureCache.Set("lstEmps", db.Employees.ToList());  
  11.                   
  12.                 return RedirectToAction("Index");  
  13.               
  14.             }  

Update the DeleteConfirmed action code to the following code,

  1. [HttpPost, ActionName("Delete")]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult DeleteConfirmed(int id)  
  4. {  
  5.     Employee employee = db.Employees.Find(id);  
  6.     db.Employees.Remove(employee);  
  7.     db.SaveChanges();  
  8.     AzureCache.Set("lstEmps", db.Employees.ToList());  
  9.     return RedirectToAction("Index");  
  10. }  

Now, test your application.

Use Azure Redis Cache With MVC And Entity Framework