I have an existing project where I want to use an ObjectDataSource
for a large data set which pages the results for a DevExpress Grid.
Examples of the code are shown below.
I am having trouble using an Entity Framework context in static methods that are required for the ObjectDataSource.
My problem is that I get this exception:
System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Does anyone know how I can change the below to support passing an Entities
instance from the Page to the static methods?
This is the example of the ObjectDataSource
<dx:ASPxGridView ID="DefinedReportGrid" runat="server" EnableTheming="True" Theme="Office2010Blue" EnableViewState="False"
ClientInstanceName="DefinedReportGrid" DataSourceForceStandardPaging="True" DataSourceID="ReportDataSource">
<SettingsPager PageSize="30"></SettingsPager>
</dx:ASPxGridView>
<asp:ObjectDataSource ID="ReportDataSource" runat="server" EnablePaging="True"
StartRowIndexParameterName="startRecord" MaximumRowsParameterName="maxRecords" SelectCountMethod="GetPageCount" SelectMethod="GetData"
TypeName="ReportService">
</asp:ObjectDataSource>
This is my service class with static methods that can then be used by the ObjectDataSource
public class ReportService
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public static DataTable GetData(int startRecord, int maxRecords)
{
// Use EF DbContent and LINQ Query to fetch paged data, and return a DataTable
// The data is PIVOTED in the code before returning it as a DataTable
return outputTable;
}
public static List<int> GetWeeks()
{
// This also requires use of the EF DbContent
...
}
public static int GetPageCount()
{
// This also requires use of the EF DbContent
// Used to count the full data for applying the correct total Page Count
...
}
}
This is the code behind for the web forms page
public partial class DefinedReport : System.Web.UI.Page
{
private Entities _modelContext = ((Global)HttpContext.Current.ApplicationInstance).Entities;
protected void Page_Init(object sender, EventArgs e)
{
...
}
protected void Page_Load(object sender, EventArgs e)
{
...
}
}
This is the global code, where the Entities context is being set on the begin and end of the request.
public class Global : HttpApplication
{
public Entities Entities { get; set; }
...
private void Application_BeginRequest(object sender, EventArgs e)
{
Entities = new Entities();
}
private void Application_EndRequest(object sender, EventArgs e)
{
if (Entities != null)
{
Entities.Dispose();
}
}
}