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
};