none
Relationship not saved when using DbContext API RRS feed

  • Question

  • I am using VS2010, EF4 and DbContext API templates with the following configuration

    DbContext.Configuration.AutoDetectChangesEnabled = false;
    DbContext.Configuration.LazyLoadingEnabled = false;
    DbContext.Configuration.ProxyCreationEnabled = false;

    I have to simple objects, A and B, with a many-to-many relationship but I am having trouble saving the relations. A simplified save-method could look like this;

    public void B_Save(B myobj)
    {
      DbContext.Entry(myobj).State = EntityState.Added;
      DbContext.SaveChanges();
    }

    This correctly saves "myobj" but the relations to object A is not saved.

    If I call DbContext.ChangeTracker.DetectChanges(); the relations are saved but I fear that calling this method could affect objects I do not want to save and furthermore, if calling this method is the correct to do, I am not sure how I remove relations?

    Monday, May 28, 2012 4:39 PM

Answers

  • Solution

    public void MyObj_Save(MyObj myobj, List<OtherObj> otherObjList)
    {
      DbContext.Entry(myobj).State = EntityState.Added;
     
      foreach (OtherObj otherObj in otherObjList)
      {
        (((System.Data.Entity.Infrastructure.IObjectContextAdapter)DbContext).ObjectContext).ObjectStateManager.ChangeRelationshipState(myobj, otherObj, q => q.OtherObjs, EntityState.Added);
      }
     
      DbContext.SaveChanges();
    }
    • Marked as answer by _keysersoze_ Tuesday, May 29, 2012 4:57 PM
    Tuesday, May 29, 2012 4:57 PM

All replies

  •   

    Where / When did you attached the A object to myobj?

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Monday, May 28, 2012 5:18 PM
  • I have tried several places - when I create object B

    using (var mycontext = new BusinessLayer.Business())
    {
      var myobj = new B();

      myobj.A = mycontext.A_GetObjects();

      mycontext.B_Save(myobj);
    }

    and also in my Save method like this;

    public void B_Save(B myobj, List<A> relations)
    {
      foreach (A otherobj in relations)
      {
        myobj.A.Add(otherobj);
      }

      DbContext.Entry(myobj).State = EntityState.Added;

      DbContext.SaveChanges();
    }

    Monday, May 28, 2012 5:35 PM
  • Solution

    public void MyObj_Save(MyObj myobj, List<OtherObj> otherObjList)
    {
      DbContext.Entry(myobj).State = EntityState.Added;
     
      foreach (OtherObj otherObj in otherObjList)
      {
        (((System.Data.Entity.Infrastructure.IObjectContextAdapter)DbContext).ObjectContext).ObjectStateManager.ChangeRelationshipState(myobj, otherObj, q => q.OtherObjs, EntityState.Added);
      }
     
      DbContext.SaveChanges();
    }
    • Marked as answer by _keysersoze_ Tuesday, May 29, 2012 4:57 PM
    Tuesday, May 29, 2012 4:57 PM