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

后端 未结 10 2238
清酒与你
清酒与你 2020-12-01 23:21

I am using EF 4 to retrieve a list of Employees.

public ContentResult AutoCompleteResult(string searchText)
{
    List list = Employee.GetAll         


        
10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 00:04

    Thought I would chime in here with my 2 cents. We had a very big data access layer, and one of the programmers was used to using a using statement for the context like so:

    using (EntityModel myContext = EntityConnection)
    {
        //code in here to grab data
    }
    

    We are using the EntityConnection as a static property that serves up a dbContext per current HttpContext. Any method called after his using block would throw the exception 'ObjectContext instance has been disposed' since obviously the context was disposed of after his method call. So if you are only using one entity context per HttpContext, make sure you don't allow the garbage collector to dispose of it by using a using block.

    I figured I would throw this in the answers since I know a lot of people use the entity context differently and I see a lot of using blocks in code samples out there.

提交回复
热议问题