CreateDetachedCopy reference issue

Thread is closed for posting
2 posts, 0 answers
  1. Vinay
    Vinay avatar
    1 posts
    Member since:
    Aug 2011

    Posted 04 Mar 2013 Link to this post


    I have following code:

    Employee dbEmployee = null;
    Employee detachedEmployee = null;
    using (DataModel model = new DataModel(ConnectionManager.ConStr))
           dbEmployee = model.Employee.FirstOrDefault(v => v.EmployeeID == 1);
         detachedEmployee = model.CreateDetachedCopy<Employee>(dbEmployee, emp=> emp.Contact);
    using (DataModel model = new DataModel(ConnectionManager.ConStr))
          Contact dbContact = null;
          Contact detachedContact = null;
          dbContact = model.Contacts.Where(contact => contact.ContactID == 1).FirstOrDefault();
          detachedContact = model.CreateDetachedCopy<Contact>(dbContact);
         detachedEmployee.Contact = detachedContact;

    In the above code I am detaching the objects. The intent is to persist them in a queue.
    But before detaching the main(Employee) object, I want the it to be updated with the associated objects
    (Foreign Keys). 
    I have tried following:
    • Detaching the Employee object in the end (in this case I don't detach the associated objects) in multiple contexts.
    • Detaching the Employee object in the beginning in a separate context and detaching its related objects in a different context.
    • Detaching only Employee object in the end in a single context.

    In all cases I get error regarding:
    Object references between two different object scopes are not allowed.
    The object 'Contact' is already managed by 'ObjectScopeImpl 0xd' and was tried to be managed
    again by 'ObjectScopeImpl 0xa'.

    As far as I have read once the object is detached, the context does not reference it.
    Also, can I face any problem in terms of performance if I serialize the data model objects in a queue.
    They will be read from MSMQ and saved in DB.

  2. Damyan Bogoev
    Damyan Bogoev avatar
    581 posts

    Posted 07 Mar 2013 Link to this post

    Hi Vinay,

    You could handle the error behavior using the OpenAccessContext.PersistenceState.IsDetached(entity) helper method before trying to attach it to an OpenAccessContext, Based on the check you have to implement the corresponding logic. Additional helpful information can be found here.

    Hope that helps.

    Damyan Bogoev
    the Telerik team
    OpenAccess ORM Q1 2013 is out featuring Multi-Diagrams, Persistent Data Stream Support and much more. Check out all of the latest highlights.
Back to Top