none
An entity object cannot be referenced by multiple instances of IEntityChangeTracker RRS feed

  • Question

  • I am trying to save facebook friend list in database.

    Now, I have UserFBFriend class in Identity model.

    and it has collection object in ApplicationUser

    it has one to many relationship with application user
    Now, I am trying to save Users Facebook friend list obtain by facebook Api's
    to database under UserFBFriend table. 

    to save I have written following method in repository

    private ApplicationDbContext context = new ApplicationDbContext();

    //other methods

    public bool SaveUserFBFriends(List<UserFBFriends> friends)
    {

            foreach (UserFBFriends value in friends)
                {
                                  context.UserFBFriends.Add(value);
                                   context.SaveChanges();
                }
    }

    When I am trying to run I am getting following error. 
    [InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.]
    Stack trace is as follow:

    [InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.] System.Data.Entity.Core.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity) +178 System.Data.Entity.Core.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet) +651 System.Data.Entity.Core.Objects.DataClasses.EntityReference.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach) +87 System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach) +58 System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach) +289 System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach) +234 System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach) +229 System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity) +652 System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +202 System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity) +165 System.Data.Entity.DbSet`1.Attach(TEntity entity) +70 Campus.Core.Repositories.Implementation.UserRepository.SaveUserFBFriends(List`1 friends) in c:\Users\rohit\Source\Workspaces\Bundle\CampusBundle\Campus.Core\Repositories\Implementation\UserRepository.cs:182 Campus.Central.Services.Implementation.UserService.SaveFrndList(String id, String accessToken) in c:\Users\rohit\Source\Workspaces\Bundle\CampusBundle\Campus.Central\Services\Implementation\UserService.cs:391 Campus.Central.Controllers.EventController.AutoComplete(String term) in c:\Users\rohit\Source\Workspaces\Bundle\CampusBundle\Campus.Central\Controllers\EventController.cs:217 lambda_method(Closure , ControllerBase , Object[] ) +127 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +242 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39 System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;BeginInvokeSynchronousActionMethod&gt;b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +12 System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +139 System.Web.Mvc.Async.AsyncInvocationWithFilters.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3d() +112 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass46.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3f() +452 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass33.&lt;BeginInvokeActionMethodWithFilters&gt;b__32(IAsyncResult asyncResult) +15 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass2b.&lt;BeginInvokeAction&gt;b__1c() +37 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass21.&lt;BeginInvokeAction&gt;b__1e(IAsyncResult asyncResult) +241 System.Web.Mvc.Controller.&lt;BeginExecuteCore&gt;b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19 System.Web.Mvc.MvcHandler.&lt;BeginProcessRequest&gt;b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +288

    I tried different options from google search non is working for me. 

    Please help 

    Thanks in advance

    Monday, October 13, 2014 6:33 PM

Answers

  • Hello RohitVy,

    Is that the friends object comes from another context which is similar with OrderList object below:

    db_testEntities db1 = new db_testEntities();
    
                var OrderList = db1.Orders.ToList();
    
                db_testEntities db2 = new db_testEntities();
    
                foreach (Order order in OrderList)
    
                {
    
                    db2.Orders.Add(order);
    
                }
    

    If it is, you need to firstly detach entities in OrderList from the db1 conext as below since they are tracked by db1 currently:

    foreach (Order order in OrderList)
    
                {
    
                    db1.Entry(order).State = EntityState.Detached;
    
                    db2.Orders.Add(order);
    
                }
    

    Regards.

    Fred.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, October 16, 2014 5:42 AM
    Moderator

All replies

  • It looks to me that you should be adding all the child objects into the collection in the parent object, and you do the SaveChanges() only one time after all the childern are added.
    Monday, October 13, 2014 6:58 PM
  • Hello darnolad924 

    Thanks for reply. 

    are you suggesting like this ?

    foreach (UserFBFriends value in friends)
                {
                                  context.UserFBFriends.Add(value);
                 

                }

                      context.SaveChanges();

    tried this but same error at    context.UserFBFriends.Add(value);  line

    Monday, October 13, 2014 8:51 PM
  • http://www.ordina.nl/nl-nl/blogs/2013/februari/entity-framework-in-a-multi-layered-application/

    The link may help you I don't know.

    But I would ask that when was it that you got the parent object and brought it into context so that you could add child objects in the parnet's collection and do a Savechanges() on the parent object in context?

    Monday, October 13, 2014 9:19 PM
  • Hello RohitVy,

    Is that the friends object comes from another context which is similar with OrderList object below:

    db_testEntities db1 = new db_testEntities();
    
                var OrderList = db1.Orders.ToList();
    
                db_testEntities db2 = new db_testEntities();
    
                foreach (Order order in OrderList)
    
                {
    
                    db2.Orders.Add(order);
    
                }
    

    If it is, you need to firstly detach entities in OrderList from the db1 conext as below since they are tracked by db1 currently:

    foreach (Order order in OrderList)
    
                {
    
                    db1.Entry(order).State = EntityState.Detached;
    
                    db2.Orders.Add(order);
    
                }
    

    Regards.

    Fred.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, October 16, 2014 5:42 AM
    Moderator