dangerisgo
dangerisgo

Reputation: 1269

Detaching object from context in entity

I'm currently using Entity Framework 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 didn't work.

Upvotes: 0

Views: 2558

Answers (1)

Michael Brown
Michael Brown

Reputation: 9153

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.

Upvotes: 2

Related Questions