سؤال

i have a multitier application using EF5 database first - ADO.NET and MVC4, and i have a issue when i try to load some properties without EF. i mean lets say i have an entity A like:

A
{
     public int id {set; get;}
     public string name {set; get;}
     public virtual ICollection<B> B { get; set; }
}

so in some cases i already have the B collection loaded from another reason and i need to assign it to A

like a simple:

a.B = b;

this happens on my business logic layer so the dbcontext had being disposed long time ago

but when i try to access the B property i only get an System.ObjectDisposedException and an error message that says

any know how to solve this?

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

هل كانت مفيدة؟

المحلول

This happens because the A object was loaded in a context that had both ProxyCreationEnabled = true and LazyLoadingEnabled = true. The A object, therefore, is a proxy object that still tries to trigger lazy loading when its child collections are accessed.

So you can disable one of these properties to prevent lazy loading after the context is disposed. Alternatively, or additionally, you can load a with its B collection loaded by using Include:

a = context.As.Include(a => a.B).Single(...);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top