1

I'm building my application using User Controls so I have Main Form and I display User Controls with this code:

        Modules.CtrlListContractors mo = new Modules.CtrlListContractors();
        splitContainerControl.Panel1.Controls.Clear();
        splitContainerControl.Panel1.Controls.Add(mo);

and within User Control I can put anything with it but my problem about this error message :

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

I have some relations with my tables that is displayed as GridView inside CtrlListContractors and when I click the menu button to show CtrlListContractors I get the above error message and I think it's because about Lazy Loading so it will need to execute more queries to get additional data from related tables.

I have this code to execute at User Control Load event:

using (ContractorsEntities context = new ContractorsEntities(Properties.Settings.Default.Connection))
        {
            memberBindingSource.DataSource = context.Members.ToList();
        }

I think the problem will be solved if I can get all data from main table and related tables at the same query before ObjectContext get disposed

4

1 回答 1

3

If you want to dispose the ObjectContext (or DbContext), you'll have to grab all the data you need first. Including the related entities.

That can be done using Include, there are two overloads: Include(string) and more strongly typed Include (available from EF 4.1)

So, assuming there's a relationship Member (0-1) ---- (*) Contractors, you can Include the collection:

context.Members.Include(x => x.Contractors).ToList();

But as I said, you'd have to include everything you need before disposing the context. Either that or don't dispose the context and lazily load the details.

于 2013-05-04T08:59:38.827 回答