views:

746

answers:

1

I'm currently using EF and am running into this issue:

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

For the page load sequence, I am filling dropdownlists via this:

using (DatabaseEntities db = new DatabaseEntities())
  {
   MyDictionary = new Dictionary<Guid, Person>();
   var List= from emp in db.Set select emp;
   ...

   foreach (Employee emp in List)
   {
    MyDictionary.Add(emp.id, emp);

The other function is a 'Next' button to close this page and open another one.

private void StoreInfo()
 {
        Person theLead= MyDictionary[new Guid(this.Lead.SelectedValue)]; 
  ....
  this.Selected.Lead= theLead;

I am storing a dictionary in the Session state here

public Dictionary<Guid,Person> MyDictionary
 {
  get
  {
   return Session["MyDictionary"] as Dictionary<Guid,Person>;
  }
  set
  {
   Session["MyDictionary"] = value;
  }
 }

How do I go about detaching each person from the first context so I can continue with the validation in the page? I have tried

db.Detach(emp)

before the

MyDictionary.Add(emp.id, emp);

but it didnt work. Any help woudl be greatly appreciated. Thanks.

+2  A: 

Instead of storing the entire entity in the Session, just use the ID and retrieve it on the next page. Embracing the statelessness of the web helps you maintain your sanity.

If you must store the entire entity, keep the Detach but when you start your new operation remember to Attach it to the new ObjectContext.

Mike Brown
I wasn't detaching the other entity that this one was being added to, so i was getting conflicted contexts
dangerisgo