Solving “The ObjectContext instance has been disposed and can no longer be used for operations that require a connection” InvalidOperationException

前端 未结 7 2108
再見小時候
再見小時候 2020-11-22 06:38

I am trying to populate a GridView using Entity Frameworkm but every time I am getting the following error:

\"Property accessor \'LoanPro

相关标签:
7条回答
  • 2020-11-22 07:08

    The CosisEntities class is your DbContext. When you create a context in a using block, you're defining the boundaries for your data-oriented operation.

    In your code, you're trying to emit the result of a query from a method and then end the context within the method. The operation you pass the result to then tries to access the entities in order to populate the grid view. Somewhere in the process of binding to the grid, a lazy-loaded property is being accessed and Entity Framework is trying to perform a lookup to obtain the values. It fails, because the associated context has already ended.

    You have two problems:

    1. You're lazy-loading entities when you bind to the grid. This means that you're doing lots of separate query operations to SQL Server, which are going to slow everything down. You can fix this issue by either making the related properties eager-loaded by default, or asking Entity Framework to include them in the results of this query by using the Include extension method.

    2. You're ending your context prematurely: a DbContext should be available throughout the unit of work being performed, only disposing it when you're done with the work at hand. In the case of ASP.NET, a unit of work is typically the HTTP request being handled.

    0 讨论(0)
提交回复
热议问题