Question

I'm new in the use of Entity Framework and i have this problem :

    List<Metier> listofjobs = new List<Metier>();
    Guid userId;
    WorkEntities notrecontexte;
    Candidat CurrentCandidat;

    protected void Page_Load(object sender, EventArgs e)
    {
        userId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
        notrecontexte = new WorkEntities ();
        CurrentCandidat = notrecontexte.Candidat
            .Include("Metier1")
            .Include("Mobilite1")
            .Include("NiveauDuDiplome1")
            .Include("NiveauDuPoste1")
            .Include("Disponibilite_Candidat")
            .Include("Contrats1")
            .First(x => x.UserId.Equals(userId) == true);
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        listofjobs = (List<Metier>)Session["listofjobs"];
        if (listofjobs != null)
        {
            CurrentCandidat.Metier1.Clear();
            try
            {
                notrecontexte.SaveChanges();
            }
            catch { }

            for (int i = 0; i < listofjobs.Count; i++)
            {
                CurrentCandidat.Metier1.Add(listofjobs[i]);
                try
                {
                    notrecontexte.SaveChanges();
                }
                catch { }
            }
        }
    }

 protected void Button1_Click(object sender, EventArgs e)
        {
            if ((List<Metier>)Session["listofjobs"] != null)
            {
             listofjobs = (List<Metier>)Session["listofjobs"];
            }
            string newjob = tbAddMetier.Text;
            Metier m = new Metier { Lebelle = newjob };
            tbAddMetier.Text = "";

            listofjobs.Add(m);
            rptrMetier.DataSource = listofjobs;
            rptrMetier.DataBind();
            C_Compte.Update();

            Session["listofjobs"] = listofjobs;
        }

        protected void ImageButton1_Click(object sender, CommandEventArgs e)
        {
            if ((List<Metier>)Session["listofjobs"] != null)
            {

                listofjobs = (List<Metier>)Session["listofjobs"];
            }
            string newjob = e.CommandArgument.ToString().Split(',')[0];
            listofjobs.Remove(listofjobs.Find(x => x.Lebelle == newjob));
            rptrMetier.DataSource = listofjobs;
            rptrMetier.DataBind();
            C_Compte.Update();
            Session["listofjobs"] = listofjobs;
        }

I have problem in these lines :

CurrentCandidat.Metier1.Add(listofjobs[i]);
try
{
    notrecontexte.SaveChanges();
}
catch { }

when i try to save the changes i got this exception The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects. .

  1. What are the reasons of this exception?
  2. How can i fix it?
Was it helpful?

Solution

Entity Framework has a context dependent behaviour. If an entity belongs to an instance of a context, you cannot use it in another instance of context unless you detach the entity from the first context and attach to the second.

For your case, at the point where you save your list of entities to the session, you need to detach the list first, and at the button click event, you need to attach listofJobs to the your current context.

I am not clear about your program flow but, if you can attach the list right after every listofjobs = (List<Metier>)Session["listofjobs"]; and detach right before every Session["listofjobs"] = listofjobs; that might work.

You can see how to detach and attach objects in Entity framework you can use links below: http://msdn.microsoft.com/en-us/library/vstudio/bb896271(v=vs.100).aspx http://msdn.microsoft.com/en-us/library/vstudio/bb896245(v=vs.100).aspx http://msdn.microsoft.com/en-us/library/vstudio/bb738697(v=vs.100).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top