Reputation: 10254
I have two methods using the EF4 - one which returns a list of objects (Pages) within a using block, and another which creates a different type of object (Book). One of the properties on Book is FirstPage, which is an item from the first list of items. When I try to set the FirstPage property on this instantiated object, I get an exception:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
I guess this must be because the using block has disposed before the object was detached. Is there any way to either 1) detach it after the context has been disposed or 2) atach it to a ghost context until I pass it back to the data layer?
This is my code:
IEnumerable<Page> allPages = null;
using (var db = new DataContainer())
{
var items = db.Pages;
var filteredCode = items.Where(i => i.Code == PageCode);
allPages = filteredCode.ToList();
}
Page page = allPages.FirstOrDefault(p => ...); // query omitted
var book = new Book()
{
Title = @"asdas",
FirstPage = page, // 'page' is never null
// rest omitted
};
Upvotes: 0
Views: 446
Reputation: 364279
Answer to both your questions is: no. Either use the same context for both operations or detach your entities prior to leaving scope of the using block.
If you are using POCOs you can also turn off proxy creation (=no lazy loading and dynamic change tracking) and your code will work without any changes because the proxy keeps reference to the context - POCO itself doesn't know anything about context.
Btw. there is another side effect of not detaching entity (Proxied POCO and probably also EntityObject
) before it goes out of lifetime scope of its context - it causes memory leak because the entity holds reference to the context and context holds references to many other objects including other attached entities. Until your entity is released (there is no reference to your entity) the garbage collector cannot release the context and all related objects.
Upvotes: 2