Data Access has been discontinued. Please refer to this page for more information.

Handling OpenAccessContext in Web Projects

This article is relevant to entity models that utilize the deprecated Visual Studio integration of Telerik Data Access. The current documentation of the Data Access framework is available here.

One of the most important things regarding Telerik Data Access based applications is the handling of the OpenAccessContext inside a web application.

The most important thing you should take care of is that the OpenAccessContext class implements the IDisposable interface. It is traditionally difficult to handle those cases in a web application, because of the stateless nature of the web. However, there are three highly efficient ways of dealing with this issue:

  • Using a MasterPage - the MasterPage is common for all the pages in a web application. You can declare the OpenAccessContext as a member of the MasterPage and then accessed in all the pages code-behind methods. Read more
  • Using the HttpContext - basically, you need to create a class that is responsible for getting and setting the OpenAccessContext from/to the HttpContext. Read more
  • Creating a new instance of the context for each CRUD operation. Read more

In this tutorial you will use the second approach, i.e. handling the context using the HttpContext. Add a new class named ContextFactory in the CarRentWebSite project.

using System.Web;
using CarRentWebSite.OpenAccess;

namespace CarRentWebSite
{
   public class ContextFactory
   {
       private static readonly string contextKey = typeof( EntitiesModel ).FullName;

       public static EntitiesModel GetContextPerRequest()
       {
           HttpContext httpContext = HttpContext.Current;
           if ( httpContext == null )
           {
               return new EntitiesModel();
           }
           else
           {
               EntitiesModel context = httpContext.Items[contextKey] as EntitiesModel;

               if ( context == null )
               {
                   context = new EntitiesModel();
                   httpContext.Items[contextKey] = context;
               }

               return context;
           }
       }
   }
}
Imports CarRentWebSite.OpenAccess

Public Class ContextFactory
    Private Shared ReadOnly contextKey As String = GetType(EntitiesModel).FullName

    Public Shared Function GetContextPerRequest() As EntitiesModel
        Dim _httpContext As HttpContext = HttpContext.Current
        If _httpContext Is Nothing Then
            Return New EntitiesModel()
        Else
            Dim context As EntitiesModel = TryCast(_httpContext.Items(contextKey), EntitiesModel)

            If context Is Nothing Then
                context = New EntitiesModel()
                _httpContext.Items(contextKey) = context
            End If

            Return context
        End If
    End Function
End Class