Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6562717
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T13:44:31+00:00 2026-05-25T13:44:31+00:00

I have strange problem with disposing entity framework connection in asp.net mvc application. I

  • 0

I have strange problem with disposing entity framework connection in asp.net mvc application.

I have simple structure for example :

Entity :

public class EmployeeReport
{
    public int EmployeeReportId { get; set; }

    public DateTime Created { get; set; }

    public Decimal Hours { get; set; }

    public string Comment { get; set; }

    public int EmployeeId { get; set; }

    public int ContractId { get; set; }

    public int ServiceId { get; set; }

    public virtual ReportContract Contract { get; set; }

    public virtual ReportService Service { get; set; }

    public virtual Employee Employee { get; set; }

}

Entity mapper :

public class EmployeeReportMapper : EntityTypeConfiguration<EmployeeReport>
{
    public EmployeeReportMapper()
    {
        ToTable("intranet_employee_reports");
        HasKey(x => x.EmployeeReportId);

        Property(x => x.Created).HasColumnName("Created").IsRequired();
        Property(x => x.Comment).HasColumnName("Comment").IsOptional();
        Property(x => x.Hours).HasColumnName("Hours").IsRequired();

        HasRequired(x => x.Employee).WithMany().HasForeignKey(x => x.EmployeeId);
        HasRequired(x => x.Service).WithMany().HasForeignKey(x => x.ServiceId);
        HasRequired(x => x.Contract).WithMany().HasForeignKey(x => x.ServiceId);
    }
}

DbContext – interface

public interface IDbContext : IDisposable
{
    IDbSet<EmployeeReport> EmployeeReports { get; }
}

DbContext – implementation

public class IntranetDbContext : DbContext,IDbContext
{
    public IDbSet<EmployeeReport> EmployeeReports { get; set; }
    ...


    public IntranetDbContext() : base("IntranetDb")
    {
        Database.SetInitializer<IntranetDbContext>(null); 
    }

    public void Commit()
    {
        SaveChanges();
    }

    public void ChangeEntityState(object entity, EntityState entityState)
    {
        Entry(entity).State = entityState;
    }

    public void ExecuteSql(string query, SqlParameterCollection parameterCollection)
    {
        Database.ExecuteSqlCommand(query, parameterCollection);
    }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        /* Register custom mapping class */
        modelBuilder.Configurations.Add(new EmployeeReportMapper());
         ....
        base.OnModelCreating(modelBuilder);
    }

}

Finally my structure map configuration :

public class CoreRegistry : Registry
{
    public CoreRegistry()
    {
        For<IDbContext>().HttpContextScoped().Use<IntranetDbContext>();
        ...
    }
}

and Global.asax :

    protected void Application_EndRequest(object sender, EventArgs e)
    {
        ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
    }

Ok, now the problem, in my application i using standard constructor dependency injection
or call ObjectFactory.GetInstance().

In one of my controller i call service class, which has access to dbcontext and fetch some entites.

Unfortunately i get classic exception :

The ObjectContext instance has been disposed and can no longer be used
for operations that require a connection.

This is strange, because service is called during request and all data are forced to client in controller…

Any idea, where I do mistake?

EDIT :

Service code :

public class EmployeeService : IEmployeeService
{
    /// <summary>
    /// IDbContext reference
    /// </summary>
    private readonly IDbContext _dbContext;

    public EmployeeService(IDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public List<Employee> GetSubordinateEmployees(Employee employee)
    {
        List<Employee> employees = new List<Employee>();

        foreach (var unit in employee.OrganizationUnits.ToList()) /* throw exception*/
        {
            foreach (var childrenUnit in unit.ChildrenUnits)
            {
                employees.AddRange(childrenUnit.Employees);
            }
        }
        return employees.Distinct().ToList();
    }

Controller :

    private readonly IEmployeeService _employeeService;

    public EmployeeReportController(IEmployeeService employeeService)
    {
        _employeeService = employeeService;
    }

    [HttpGet]
    public ActionResult SearchReports()
    {
        List<Employee> employees = _employeeService.GetSubordinateEmployee(IntranetSession.Current.LoggedAccount.Employee).ToList(); // Exception!
       ...

        return View();
    }


}   
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T13:44:32+00:00Added an answer on May 25, 2026 at 1:44 pm

    Your code doesn’t use current DbContext at all. The problem is:

    IntranetSession.Current.LoggedAccount.Employee
    

    Followed by:

    employee.OrganizationUnits.ToList()
    

    Your employee stored in session was loaded with context which is already disposed but it still keeps reference to that context. When you loaded that employee you didn’t eager load his organizations so once you access her OrganizationUnits it will try to trigger lazy loading on disposed context.

    There are two ways to avoid this problem:

    • Eager load all information you need to use from your employee stored in session. It means retrieving employee like context.Employees.Include(e => e.OrganizationUnits).Single(...)
    • Store only employee’s Id in session and load on-demand data you need

    If you want to cache whole employee in session make sure that you will disable proxy creation for objects stored in session by calling :

     context.Configuration.ProxyCreationEnabled = false;
    

    It will ensure that cached data will not keep reference to disposed context (which btw. prevent garbage collector to collect context and all its referenced objects).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a strange problem with ASP.NET. Several sites on my web server run
i have strange problem , my application (exe) is working fine in debug mode
I have a strange problem. while MicrosoftMvcValidation works in my mvc project, MicrosoftMvcJQueryValidation doesn't.
I have this web app that is running ASP .NET MVC 1.0 with LINQ
I have a strange problem where the users of my application complain about the
I have strange problem. I set a JProgressBar: private JProgressBar progressBar; public void foo()
I have a strange problem. I have created a simple function to convert from
I have strange problem with sharepoint and ajax functionality. We have an UpdatePanel placed
i have strange problem doing reporting: i have numerous clients with different issued invoices.
We have very strange problem, one of our applications is continually querying server by

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.