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

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

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

4条回答
  •  执念已碎
    2020-12-08 15:13

    You have lazy loading enabled. So when you try to load reference property there is no way to do it, because ObjectContext disposed right after using block.

    There are two ways to fix it:

    //1. Tell EF to load Country property immediately.
    using(var db = new jQGridEntities())
    {
        customers = db.Customers.Include(c => c.Country).ToList();
    }
    
    //2. Put return inside using block.
    using(var db = new jQGridEntities())
    {
        customers = db.Customers.ToList();
        return Json(/*your code*/);
    }
    

    Also you can disable lazy loading, but in that case you will get NullReferenceException, which can be also fixed using .Include(c => c.Country).

提交回复
热议问题