Caching in MVC Application With Entity Framework Using Query Notification

Introduction

Caching is very important for every web application. It allows us to store frequently used data in server memory that is available for all users. Query Notification allows us to have SQL cache dependency. Query Notification is very efficient and it allows applications to be notified when data has changed. The SqlDependency represents a Query Notification between application and SQL Server instance. Applications can create an object of SqlDependency and register it to receive a notification.

Procedure to Create Caching mechanism in MVC with Entity Framework

Step 1: Enable Service Broker and the Trustworthy property set in the database as in the following:

  1. ALTER DATABASE [Testdb] SET ENABLE_BROKER;  
  2. ALTER DATABASE [Testdb] SET TRUSTWORTHY ON;  

Step 2: Create a table and insert some dummy data as in the following:

 

  1. USE [Testdb]  
  2.   
  3. CREATE TABLE [dbo].[CategoryMaster](  
  4.                 [Id] [int] IDENTITY(1,1) NOT NULL,  
  5.                 [Name] [varchar](50) NOT NULL,  
  6.                 [Description] [varchar](50) NOT NULL,  
  7. CONSTRAINT [PK_CategoryMaster] PRIMARY KEY CLUSTERED  
  8. (  
  9.                 [Id] ASC  
  10. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  11. ON [PRIMARY]  
  12.   
  13. USE [Testdb]  
  14. GO  
  15. SET IDENTITY_INSERT [dbo].[CategoryMaster] ON  
  16. INSERT [dbo].[CategoryMaster] ([Id], [Name], [Description]) VALUES (1, N'Test 1', N'Test 1')  
  17. INSERT [dbo].[CategoryMaster] ([Id], [Name], [Description]) VALUES (2, N'Test 2', N'Test 2')  
  18. INSERT [dbo].[CategoryMaster] ([Id], [Name], [Description]) VALUES (3, N'Test 3', N'Test 3')  
  19. INSERT [dbo].[CategoryMaster] ([Id], [Name], [Description]) VALUES (4, N'Test 4', N'Test 4')  
  20. INSERT [dbo].[CategoryMaster] ([Id], [Name], [Description]) VALUES (5, N'Test 5', N'Test 5')  
  21. INSERT [dbo].[CategoryMaster] ([Id], [Name], [Description]) VALUES (6, N'Test 6', N'Test 6')  
  22. INSERT [dbo].[CategoryMaster] ([Id], [Name], [Description]) VALUES (7, N'Test 7', N'Test 7')  
  23. SET IDENTITY_INSERT [dbo].[CategoryMaster] OFF   

Step 3: Register the SQL Server instance to get notification.

We can use an Application_Start event of Global.asax to register the SQL Server instance to get notification the same as we can use an Application_End event of Global.asax to deregister the SQL Dependency.

 

  1. private static EntityConnectionStringBuilder entityConnectionString = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["TestdbEntities"].ConnectionString);  
  2.   
  3. protected void Application_Start()  
  4. {  
  5.     string connectionString = entityConnectionString.ProviderConnectionString;  
  6.     System.Data.SqlClient.SqlDependency.Start(connectionString);  
  7. }  
  8. protected void Application_End(object sender, EventArgs e)  
  9. {  
  10.     string connectionString = entityConnectionString.ProviderConnectionString;  
  11.     System.Data.SqlClient.SqlDependency.Stop(connectionString);  
  12. }  

Step 4:  Creating Caching Class

MVC does not have an object of the System.Web.Caching.Cache class. This class object can be goten from HttpContext.Current. In this class data is loaded either from a cache or from a database. It is dependent data within a cache, in other words if data is present in the cache then this class returns data from the cache else it retrieves data from the database and sets the cache dependency.

 

  1. public class Caching  
  2. {  
  3.     private static EntityConnectionStringBuilder entityConnectionString = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["TestdbEntities"].ConnectionString);  
  4.     public static IEnumerable<CategoryMaster> GetCategoryData()  
  5.     {  
  6.         IEnumerable<CategoryMaster> categoryData = HttpContext.Current.Cache.Get("Category"as IEnumerable<CategoryMaster>;  
  7.         if (categoryData == null)  
  8.         {  
  9.             using (var context = new TestdbEntities())  
  10.             {  
  11.                 IQueryable<CategoryMaster> categoryDataCache = context.CategoryMasters;  
  12.                 using (SqlConnection connection = new SqlConnection(entityConnectionString.ProviderConnectionString))  
  13.                 {  
  14.                     connection.Open();  
  15.                     SqlCommand command = new SqlCommand(((System.Data.Objects.ObjectQuery)categoryDataCache).ToTraceString(), connection);  
  16.                     SqlCacheDependency dependency = new SqlCacheDependency(command);  
  17.                     categoryData = categoryDataCache.ToList();  
  18.                     HttpContext.Current.Cache.Insert("Category", categoryData, dependency);  
  19.                     command.ExecuteNonQuery();  
  20.                 }  
  21.             }  
  22.         }  
  23.         return categoryData;  
  24.     }  
  25. }   

Example Controller Code

 

  1. public ActionResult Index()  
  2. {  
  3.     ViewBag.Message = "Welcome to ASP.NET MVC!";  
  4.     IEnumerable<CategoryMaster> categoryData = Caching.GetCategoryData();  
  5.     return View(categoryData);  
  6. }   

Example View Page Code 

 

  1. @{  
  2.     ViewBag.Title = "Home Page";  
  3. }  
  4. @model IEnumerable<MvcApplication2.CategoryMaster>  
  5.   
  6. <h2>@ViewBag.Message</h2>  
  7. @if (Model != null)  
  8. {  
  9.     <table>  
  10.         <tr>  
  11.             <td style="width:50px">Id</td>  
  12.             <td style="width:150px">Name</td>  
  13.             <td style="width:150px">Description</td>  
  14.         </tr>  
  15.         @foreach (var data in Model)  
  16.         {  
  17.             <tr>  
  18.                 <td>@data.Id</td>  
  19.                 <td>@data.Name</td>  
  20.                 <td>@data.Description</td>  
  21.             </tr>  
  22.         }  
  23.     </table>  
  24. }  
  25. else  
  26. {  
  27.     <p>No Data Found.</p>  
  28. }  

MVC Application

Summary

Query Notification and a SQLDependency object allows an application to be notified when data has changed. It does not matter how the data has changed. Sometimes Entity Framework generates a complex query that is not supported by Query Notification.      


Similar Articles