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

后端 未结 4 731
陌清茗
陌清茗 2020-12-08 14:21

I have two tables Customers and Country and use ( Entity Framework with vs 2012 )

4条回答
  •  借酒劲吻你
    2020-12-08 15:00

    You are trying to access an association property Country after the data context has been disposed. Entity Framework, by default, loads association properties lazily. In other words, it makes another trip to the database when you try to access the association property for the first time. To make this trip to the database, Entity Framework must use a data context. In your case, it would be trying to use the data context created by jQGridDemoEntities db = new jQGridDemoEntities() which has unfortunately been disposed at this point in your code. The data context has been disposed because you've exited the using block.

    You have three options to get around this problem:

    • Access the association property when the data context is still alive. More concretely, move your code where you access the association property into your using block

    • Eagerly load the association property as explained in the first link I specified

      customers = db.Customers.Include(c => c.Country).ToList()

    • Explicitly select what you want to return from the database while the data context is still alive. And use that information to construct the json object your return.

      customers = db.Customers.Select(c => new
      {
          c.Id,
          c.FirstName,
          c.LastName,
          c.Address,
          c.Email,
          c.Phone,
          CountryName = c.Country.Name,
          c.Note
      };
      

提交回复
热议问题