title: Memory leak in Entity Framework database context
body: <p>I am trying to figure out this problem for 3 days i have done lots of googling on the internet and use profile analyzer (<a href="http://www.jetbrains.com/dotmemory/" rel="nofollow">dotmemory 4.0</a>).</p>
  
  <p>I use Castle Windsor as dependency injection library and entity framework 6 code first model.
  Most of the model is taken from prodinner sample application (<a href="https://prodinner.codeplex.com/" rel="nofollow">prodinner</a>) which i have done some modifications.</p>
  
  <p>I will write the code in my data layer. I focused on data layer cause when the data in the called page increased memory leak is becoming huge. I can track that from profile analyzer.</p>
  
  <p>--------------DbContextFactory Class--------------------</p>
  
  <pre><code>     public interface IDbContextFactory:IDisposable
  {
      DbContext GetContext();
  }
  
  public class DbContextFactory : IDbContextFactory
  {
      private readonly DbContext dbContext;
      public DbContextFactory()
      {
          dbContext = new Db();
      }
  
      public DbContext GetContext()
      {
          return dbContext;
      }
  
      #region IDisposable
  
      public void Dispose()
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }
  
      protected virtual void Dispose(bool disposing)
      {
          if (disposing)
          {
              if (dbContext != null)
              {   
                  dbContext.Dispose();
              }
          }
      }
  
      #endregion  
  }
  </code></pre>
  
  <p>---------------------Db Class-----------------------------</p>
  
  <pre><code>    public class Db : DbContext
  {
      public Db()
      {
          Database.SetInitializer&lt;Db&gt;(new MigrateDatabaseToLatestVersion&lt;MediaManagerV2.Data.Db,Configuration&gt;());
      }
      public DbSet&lt;Effect&gt; Effects { get; set; }
      public DbSet&lt;Feed&gt; Feeds { get; set; }
      public DbSet&lt;File&gt; Files { get; set; }
      public DbSet&lt;FileExtension&gt; FileExtensions { get; set; }
      public DbSet&lt;Folder&gt; Folders { get; set; }
      public DbSet&lt;Layer&gt; Layers { get; set; }
      public DbSet&lt;RepeatSetting&gt; RepeatSettings { get; set; }
      public DbSet&lt;RepeatSettingsWeekDay&gt; RepeatSettingsWeekDays { get; set; }
      public DbSet&lt;Role&gt; Roles { get; set; }
      public DbSet&lt;Notification&gt; Notifications { get; set; }
      public DbSet&lt;Schedule&gt; Schedules { get; set; }
      public DbSet&lt;ScheduleFile&gt; ScheduleFiles { get; set; }
      public DbSet&lt;ScheduleLayer&gt; ScheduleLayers { get; set; }
      public DbSet&lt;SchedulePosition&gt; SchedulePositions { get; set; }
      public DbSet&lt;SchedulePlayList&gt; SchedulePlayLists { get; set; }
      public DbSet&lt;SchedulePlayListFile&gt; SchedulePlayListFiles { get; set; }
      public DbSet&lt;ScheduleScreen&gt; ScheduleScreens { get; set; }
      public DbSet&lt;ScheduleSetting&gt; ScheduleSettings { get; set; }
      public DbSet&lt;Screen&gt; Screens { get; set; }
      public DbSet&lt;ScreenCommandConsole&gt; ScreenCommandConsoles { get; set; }
      public DbSet&lt;ScreenCommandMagicInfo&gt; ScreenCommandMagicInfoes { get; set; }
      public DbSet&lt;ScreenGroup&gt; ScreenGroups { get; set; }
      public DbSet&lt;Setting&gt; Settings { get; set; }
      public DbSet&lt;SubFile&gt; SubFiles { get; set; }
      public DbSet&lt;Template&gt; Templates { get; set; }
      public DbSet&lt;User&gt; Users { get; set; }
      public DbSet&lt;UserRole&gt; UserRoles { get; set; }
      public DbSet&lt;UserNotification&gt; UserNotifications { get; set; }
      public DbSet&lt;SchemaContent&gt; SchemaXmls { get; set; }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Conventions.Remove&lt;ManyToManyCascadeDeleteConvention&gt;();
          modelBuilder.Conventions.Remove&lt;OneToManyCascadeDeleteConvention&gt;();
  
          modelBuilder.Configurations.Add(new FeedMap());
          modelBuilder.Configurations.Add(new FileMap());
          modelBuilder.Configurations.Add(new FileExtensionMap());
          modelBuilder.Configurations.Add(new FolderMap());
          modelBuilder.Configurations.Add(new LayerMap());
          modelBuilder.Configurations.Add(new RepeatSettingMap());
          modelBuilder.Configurations.Add(new RepeatSettingsWeekDayMap());
          modelBuilder.Configurations.Add(new RoleMap());
          modelBuilder.Configurations.Add(new NotificationMap());
          modelBuilder.Configurations.Add(new ScheduleMap());
          modelBuilder.Configurations.Add(new ScheduleFileMap());
          modelBuilder.Configurations.Add(new ScheduleLayerMap());
          modelBuilder.Configurations.Add(new SchedulePositionMap());
          modelBuilder.Configurations.Add(new SchedulePlayListMap());
          modelBuilder.Configurations.Add(new SchedulePlayListFileMap());
          modelBuilder.Configurations.Add(new ScheduleScreenMap());
          modelBuilder.Configurations.Add(new ScheduleSettingMap());
          modelBuilder.Configurations.Add(new ScreenMap());
          modelBuilder.Configurations.Add(new ScreenCommandConsoleMap());
          modelBuilder.Configurations.Add(new ScreenCommandMagicInfoMap());
          modelBuilder.Configurations.Add(new ScreenGroupMap());
          modelBuilder.Configurations.Add(new SettingMap());
          modelBuilder.Configurations.Add(new SubFileMap());
          modelBuilder.Configurations.Add(new TemplateMap());
          modelBuilder.Configurations.Add(new UserMap());
          modelBuilder.Configurations.Add(new UserRoleMap());
          modelBuilder.Configurations.Add(new UserNotificationMap());
          modelBuilder.Configurations.Add(new SchemaContentMap());
          modelBuilder.Configurations.Add(new EffectMap());
  
          base.OnModelCreating(modelBuilder);
      }
      #region IDisposable
  
      //public void Dispose()
      //{
      //    Dispose(true);
      //    GC.SuppressFinalize(this);
      //}
  
      //protected virtual void Dispose(bool disposing)
      //{
      //    if (disposing)
      //    {
      //        if (this != null)
      //        {
      //            this.Dispose();
      //        }
      //    }
      //}
  
  
      protected override void Dispose(bool disposing)
      {
          var connection = this.Database.Connection;
          base.Dispose(disposing);
          connection.Dispose();
  
          GC.SuppressFinalize(this);
      }
      #endregion
  }
  </code></pre>
  
  <p>First i was suspicious about windsor container if it is the one can not release the controller because of dbcontext. But IoC container is resolved by per-web-request then i thought it shouldn't be a problem. To be sure about it also i've added idisposable interface to IDbContextFactory, i don't know if it is the right usage cause in prodinner sample it is not used like that and according to my logic dbcontextfactory should be disposed per-web-request. </p>
  
  <p>I switched to look deeper for dbcontext i removed windsor configurations and create ExampleController which basically open a dbcontext and returning some values to view.
  But i realized that still i am getting memory increase in iis worker process when i debug it. Here is the code for examplecontroller</p>
  
  <pre><code>     public class ExampleController : Controller
  {
      //
      // GET: /Example/
  
      public ActionResult Index()
      {
          var retval = new DashboardInput();
          //var totalScreens = 2;
          //var totalOfflineScreens = 3;
          //var totalSchedules = 4;
          //var totalFileUploads = 5;
  
          //List&lt;DashboardScreenInput&gt; offlineScreenList = new List&lt;DashboardScreenInput&gt;();
          //var dashboardScreenInput = new DashboardScreenInput();
          //dashboardScreenInput.Id = 1;
          //dashboardScreenInput.LastCheckInDate = DateTime.Now.TimeAgo();
          //dashboardScreenInput.MacAddress = "10-11-12-AB-E8-D9";
          //dashboardScreenInput.Name = "Test";
          //dashboardScreenInput.ScreenUniqueIdentifier = "ACBASd";
          //offlineScreenList.Add(dashboardScreenInput);
          //offlineScreenList.Add(dashboardScreenInput);
  
          //List&lt;DashboardFeedInput&gt; feedSystemList = new List&lt;DashboardFeedInput&gt;();
          //List&lt;DashboardFeedInput&gt; feedActivityList = new List&lt;DashboardFeedInput&gt;();
  
          //var feed = new DashboardFeedInput();
          //feed.Description = "Can çok iyi";
          //feed.Label = 1;
          //feed.RecordDate = DateTime.Now.TimeAgo();
          //feed.Type = 1;
          //feedSystemList.Add(feed);
          //feedSystemList.Add(feed);
  
  
          //feedActivityList.Add(feed);
          //feedActivityList.Add(feed);
          //feedActivityList.Add(feed);
          //feedActivityList.Add(feed);
          //retval.FeedsActivity = feedActivityList;
          //retval.FeedsSystem = feedSystemList;
          //retval.OfflineScreens = offlineScreenList;
  
          //retval.TotalFileUploads = totalFileUploads;
          //retval.TotalOfflineScreens = totalOfflineScreens;
          //retval.TotalSchedules = totalSchedules;
          //retval.TotalScreens = totalScreens;
  
          using (var db = new Db())
          {
  
              var totalScreens = db.Screens.Where(o =&gt; o.UserID == 1 &amp;&amp; !o.IsDeleted).Count();
              var totalOfflineScreens = db.Screens.Where(o =&gt; !o.IsOnline &amp;&amp; o.UserID == 1 &amp;&amp; !o.IsDeleted).Count();
              var totalSchedules = db.Screens.Where(o =&gt; o.UserID == 1 &amp;&amp; !o.IsDeleted).Count();
              var totalFileUploads = db.Files.Where(o =&gt; o.UserID == 1 &amp;&amp; o.FileExtension.Extension != ".sch" &amp;&amp; o.FileExtension.Extension != ".LFD" &amp;&amp; !o.IsDeleted).Count();
  
              IEnumerable&lt;DashboardScreenInput&gt; offlineScreenList = db.Screens.Where(o =&gt; !o.IsOnline &amp;&amp; o.UserID == 1 &amp;&amp; !o.IsDeleted).OrderByDescending(o =&gt; o.LastCheckInDate).Select(o =&gt; new { Id = o.Id, Name = o.Name, LastCheckInDate = o.LastCheckInDate, MacAddress = o.MacAddress, ScreenUniqueIdentifier = o.ScreenUniqueIdentifier }).AsEnumerable().Select(o =&gt; new DashboardScreenInput { Id = o.Id, Name = o.Name, LastCheckInDate = o.LastCheckInDate.TimeAgo(), MacAddress = o.MacAddress, ScreenUniqueIdentifier = o.ScreenUniqueIdentifier }).ToList();
              IEnumerable&lt;DashboardFeedInput&gt; feedSystemList = db.Feeds.Where(o =&gt; o.Type == (byte)Enums.FeedType.System &amp;&amp; o.UserID == 1 &amp;&amp; !o.IsDeleted).OrderByDescending(o =&gt; o.RecordDate).Take(10).Select(o =&gt; new { Description = o.Description, Label = o.Label, RecordDate = o.RecordDate, Type = o.Type }).AsEnumerable().Select(o =&gt; new DashboardFeedInput { Description = o.Description, Label = o.Label, RecordDate = o.RecordDate.TimeAgo(), Type = o.Type }).ToList();
              IEnumerable&lt;DashboardFeedInput&gt; feedActivityList = db.Feeds.Where(o =&gt; o.Type == (byte)Enums.FeedType.Activity &amp;&amp; o.UserID == 1 &amp;&amp; !o.IsDeleted).OrderByDescending(o =&gt; o.RecordDate).Take(10).Select(o =&gt; new { Description = o.Description, Label = o.Label, RecordDate = o.RecordDate, Type = o.Type }).AsEnumerable().Select(o =&gt; new DashboardFeedInput { Description = o.Description, Label = o.Label, RecordDate = o.RecordDate.TimeAgo(), Type = o.Type }).ToList();
  
              retval.FeedsActivity = feedActivityList;
              retval.FeedsSystem = feedSystemList;
              retval.OfflineScreens = offlineScreenList;
  
              retval.TotalFileUploads = totalFileUploads;
              retval.TotalOfflineScreens = totalOfflineScreens;
              retval.TotalSchedules = totalSchedules;
              retval.TotalScreens = totalScreens;
          }
          return View(retval);
      }
  
  }
  </code></pre>
  
  <p>I tried also without db context as you can see in the comment lines. It doesn't give me any increase in memory. So i believe i am doing sth. wrong in my data layer. what can be the cause? Any idea is appreciated. Thank you.</p>
  
  <h2>Update 1</h2>
  
  <hr>
  
  <p>Hello again, thanks for the replies. 
  now i am suspicious about the mvc project cause now i am trying this.
  I removed everything from Global.asax, i just wanted to be sure that this application is working fine without contextfactory or windsor so my global.asax class become like this.</p>
  
  <pre><code>     public class MvcApplication : System.Web.HttpApplication
  {
      protected void Application_Start()
      {
          //Bootstrapper.Bootstrap();
          //AreaRegistration.RegisterAllAreas();
  
          //WebApiConfig.Register(GlobalConfiguration.Configuration);
          //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
          RouteConfig.RegisterRoutes(RouteTable.Routes);
      }
  
      protected void Application_AuthenticateRequest(Object sender, EventArgs e)
      {
          //if (HttpContext.Current.User == null) return;
          //if (!HttpContext.Current.User.Identity.IsAuthenticated) return;
          //if (!(HttpContext.Current.User.Identity is FormsIdentity)) return;
  
          //var id = HttpContext.Current.User.Identity as FormsIdentity;
          //var ticket = id.Ticket;
          //var userData = ticket.UserData;
          //var roles = userData.Split(new[] { ',' });
  
          //HttpContext.Current.User = new GenericPrincipal(id, roles);
      }
     }
  </code></pre>
  
  <p>after that i've created a new mvc project in vs 2012. I've created simple controller and view just to be sure that no memory leak happens when i call the new mvc project page. It worked fine as i expected. Then i copy paste the web.config file to my application so i can be sure that there's nothing wrong with my web.config file. Here is the web.config file.</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;configuration&gt;&lt;configSections&gt;
  &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt;
   &lt;/configSections&gt;
   &lt;connectionStrings&gt;
      &lt;add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication1-20140708015245;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication1-20140708015245.mdf" /&gt;
    &lt;/connectionStrings&gt;
    &lt;appSettings&gt;
      &lt;add key="webpages:Version" value="2.0.0.0" /&gt;
      &lt;add key="webpages:Enabled" value="false" /&gt;
      &lt;add key="PreserveLoginUrl" value="true" /&gt;
      &lt;add key="ClientValidationEnabled" value="true" /&gt;
      &lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt;
     &lt;/appSettings&gt;
    &lt;system.web&gt;
      &lt;httpRuntime targetFramework="4.5" /&gt;
      &lt;compilation debug="true" targetFramework="4.5" /&gt;
      &lt;authentication mode="Forms"&gt;
      &lt;forms loginUrl="~/Account/Login" timeout="2880" /&gt;
      &lt;/authentication&gt;
      &lt;pages&gt;
      &lt;namespaces&gt;
      &lt;add namespace="System.Web.Helpers" /&gt;
      &lt;add namespace="System.Web.Mvc" /&gt;
      &lt;add namespace="System.Web.Mvc.Ajax" /&gt;
      &lt;add namespace="System.Web.Mvc.Html" /&gt;
      &lt;add namespace="System.Web.Optimization" /&gt;
      &lt;add namespace="System.Web.Routing" /&gt;
      &lt;add namespace="System.Web.WebPages" /&gt;
    &lt;/namespaces&gt;
  &lt;/pages&gt;
  &lt;profile defaultProvider="DefaultProfileProvider"&gt;
    &lt;providers&gt;
      &lt;add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" /&gt;
    &lt;/providers&gt;
  &lt;/profile&gt;
  &lt;membership defaultProvider="DefaultMembershipProvider"&gt;
    &lt;providers&gt;
      &lt;add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /&gt;
    &lt;/providers&gt;
  &lt;/membership&gt;
  &lt;roleManager defaultProvider="DefaultRoleProvider"&gt;
    &lt;providers&gt;
      &lt;add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" /&gt;
    &lt;/providers&gt;
  &lt;/roleManager&gt;
  &lt;!--
          If you are deploying to a cloud environment that has multiple web server instances,
          you should change session state mode from "InProc" to "Custom". In addition,
          change the connection string named "DefaultConnection" to connect to an instance
          of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
    --&gt;
  &lt;sessionState mode="InProc" customProvider="DefaultSessionProvider"&gt;
    &lt;providers&gt;
      &lt;add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" /&gt;
    &lt;/providers&gt;
  &lt;/sessionState&gt;
  &lt;/system.web&gt;
  &lt;system.webServer&gt;
     &lt;validation validateIntegratedModeConfiguration="false" /&gt;
     &lt;handlers&gt;
       &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /&gt;
       &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /&gt;
       &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0" /&gt;
       &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /&gt;
        &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /&gt;
        &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt;
         &lt;/handlers&gt;
       &lt;/system.webServer&gt;
       &lt;runtime&gt;
         &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt;
         &lt;dependentAssembly&gt;
         &lt;assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /&gt;
         &lt;bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /&gt;
        &lt;bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /&gt;
       &lt;/dependentAssembly&gt;
       &lt;dependentAssembly&gt;
         &lt;assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /&gt;
        &lt;bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt;
       &lt;/dependentAssembly&gt;
       &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" /&gt;
       &lt;/dependentAssembly&gt;
    &lt;dependentAssembly&gt;
      &lt;assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /&gt;
      &lt;bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" /&gt;
    &lt;/dependentAssembly&gt;
  &lt;/assemblyBinding&gt;
    &lt;/runtime&gt;
    &lt;entityFramework&gt;
      &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,    EntityFramework" /&gt;
    &lt;/entityFramework&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>And i have used the same class that i used in my first post ExampleController. This time i used only hardcoded values that i have given. Here is the code.</p>
  
  <pre><code> public class ExampleController : Controller
  {
      //
      // GET: /Example/
  
      public ActionResult Index()
      {
          var retval = new DashboardInput();
          var totalScreens = 2;
          var totalOfflineScreens = 3;
          var totalSchedules = 4;
          var totalFileUploads = 5;
  
          List&lt;DashboardScreenInput&gt; offlineScreenList = new List&lt;DashboardScreenInput&gt;();
          var dashboardScreenInput = new DashboardScreenInput();
          dashboardScreenInput.Id = 1;
          dashboardScreenInput.LastCheckInDate = DateTime.Now.TimeAgo();
          dashboardScreenInput.MacAddress = "10-11-12-AB-E8-D9";
          dashboardScreenInput.Name = "Test";
          dashboardScreenInput.ScreenUniqueIdentifier = "ACBASd";
          offlineScreenList.Add(dashboardScreenInput);
          offlineScreenList.Add(dashboardScreenInput);
  
          List&lt;DashboardFeedInput&gt; feedSystemList = new List&lt;DashboardFeedInput&gt;();
          List&lt;DashboardFeedInput&gt; feedActivityList = new List&lt;DashboardFeedInput&gt;();
  
          var feed = new DashboardFeedInput();
          feed.Description = "Can çok iyi";
          feed.Label = 1;
          feed.RecordDate = DateTime.Now.TimeAgo();
          feed.Type = 1;
          feedSystemList.Add(feed);
          feedSystemList.Add(feed);
  
  
          feedActivityList.Add(feed);
          feedActivityList.Add(feed);
          feedActivityList.Add(feed);
          feedActivityList.Add(feed);
  
          retval.FeedsActivity = feedActivityList;
          retval.FeedsSystem = feedSystemList;
          retval.OfflineScreens = offlineScreenList;
  
          retval.TotalFileUploads = totalFileUploads;
          retval.TotalOfflineScreens = totalOfflineScreens;
          retval.TotalSchedules = totalSchedules;
          retval.TotalScreens = totalScreens;
  
  
          //using (var db = new Db())
          //{
  
          //    var totalScreens = db.Screens.Where(o =&gt; o.UserID == 1 &amp;&amp; !o.IsDeleted).Count();
          //    var totalOfflineScreens = db.Screens.Where(o =&gt; !o.IsOnline &amp;&amp; o.UserID == 1 &amp;&amp; !o.IsDeleted).Count();
          //    var totalSchedules = db.Screens.Where(o =&gt; o.UserID == 1 &amp;&amp; !o.IsDeleted).Count();
          //    var totalFileUploads = db.Files.Where(o =&gt; o.UserID == 1 &amp;&amp; o.FileExtension.Extension != ".sch" &amp;&amp; o.FileExtension.Extension != ".LFD" &amp;&amp; !o.IsDeleted).Count();
  
          //    IEnumerable&lt;DashboardScreenInput&gt; offlineScreenList = db.Screens.Where(o =&gt; !o.IsOnline &amp;&amp; o.UserID == 1 &amp;&amp; !o.IsDeleted).OrderByDescending(o =&gt; o.LastCheckInDate).Select(o =&gt; new { Id = o.Id, Name = o.Name, LastCheckInDate = o.LastCheckInDate, MacAddress = o.MacAddress, ScreenUniqueIdentifier = o.ScreenUniqueIdentifier }).AsEnumerable().Select(o =&gt; new DashboardScreenInput { Id = o.Id, Name = o.Name, LastCheckInDate = o.LastCheckInDate.TimeAgo(), MacAddress = o.MacAddress, ScreenUniqueIdentifier = o.ScreenUniqueIdentifier }).ToList();
          //    IEnumerable&lt;DashboardFeedInput&gt; feedSystemList = db.Feeds.Where(o =&gt; o.Type == (byte)Enums.FeedType.System &amp;&amp; o.UserID == 1 &amp;&amp; !o.IsDeleted).OrderByDescending(o =&gt; o.RecordDate).Take(10).Select(o =&gt; new { Description = o.Description, Label = o.Label, RecordDate = o.RecordDate, Type = o.Type }).AsEnumerable().Select(o =&gt; new DashboardFeedInput { Description = o.Description, Label = o.Label, RecordDate = o.RecordDate.TimeAgo(), Type = o.Type }).ToList();
          //    IEnumerable&lt;DashboardFeedInput&gt; feedActivityList = db.Feeds.Where(o =&gt; o.Type == (byte)Enums.FeedType.Activity &amp;&amp; o.UserID == 1 &amp;&amp; !o.IsDeleted).OrderByDescending(o =&gt; o.RecordDate).Take(10).Select(o =&gt; new { Description = o.Description, Label = o.Label, RecordDate = o.RecordDate, Type = o.Type }).AsEnumerable().Select(o =&gt; new DashboardFeedInput { Description = o.Description, Label = o.Label, RecordDate = o.RecordDate.TimeAgo(), Type = o.Type }).ToList();
  
          //    retval.FeedsActivity = feedActivityList;
          //    retval.FeedsSystem = feedSystemList;
          //    retval.OfflineScreens = offlineScreenList;
  
          //    retval.TotalFileUploads = totalFileUploads;
          //    retval.TotalOfflineScreens = totalOfflineScreens;
          //    retval.TotalSchedules = totalSchedules;
          //    retval.TotalScreens = totalScreens;
          //    db.SaveChanges();
          //}
          return View(retval);
      }
  
  }
  </code></pre>
  
  <p>and as a result it continues to increase memory by nearly 1mb in every page refresh. I couldn't understand why is this happening? Any other configuration that i don't know in mvc?</p>