none
I don't understand the purpose of EntityCollection.Attach and EntityReference.Attach RRS feed

  • Question

  • hi

    ObjectContext.Attach and ObjectSet.Attach are used to attach a detached entity ( which already exists in a DB ) to a context – this way when ObjectContext.SaveChanges is called, EF doesn't try to send an insert command for this attached entity

    But I don't understand the purpose of EntityCollection.Attach and EntityReference.Attach. Namely, the two methods can only attach entities that are already managed by ObjectContext ( thus they can't be used to attach entities with EntityState set to Added or Detached ).

    And since entities managed by ObjectContext already have their relationships automatically resolved ( ie their EntityReference property returns a parent entity and their EntityCollection property contains related child entities ), I fail to understand what exactly would we gain by using EntityCollection.Attach or EntityReference.Attach to attach a related entity E1 to a particular entity E2, since E1 was already attached to E2 automatically by ObjectContext?

    Thank you

     

     




    • Edited by KlemS100 Wednesday, November 16, 2011 4:36 PM
    Wednesday, November 16, 2011 4:33 PM

All replies

  • Can't someone please help me with this?
    Thursday, November 17, 2011 7:20 PM
  • Hi Klem,

    I think you can refer this link: http://msdn.microsoft.com/en-us/library/bb896416(v=vs.90).aspx

    When we load the related objects from the tracked entity, it will use entitycollection.attach method to create the relationship. 

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Sunday, November 20, 2011 9:30 AM
    Moderator
  • 1)

    When we load the related objects from the tracked entity, it will use entitycollection.attach method to create the relationship. 

    When we retrieve related entities from the DB, ObjectContext automatically resolves the relationships. Are you saying that under the hood ObjectContext uses EntitCollection.Attach and EntityReference.Attach to resolve the relationship?

    2) Still, my original question is still valid -  what exactly would we gain by using EntityCollection.Attach orEntityReference.Attach to attach a related entity E1 to a particular entity E2, since E1 was already attached to E2 automatically by ObjectContext?

     

    thank you

    Monday, November 21, 2011 5:48 PM
  • I know pestering for an answer is against the rules, so I've never done it for any of my other threads, but this thing is really bugging me - isn't there anybody that would be willing to help me with my questions?
    Wednesday, November 23, 2011 6:12 PM