AttachCopy and identities for inserted entities

Thread is closed for posting
3 posts, 1 answers
  1. Fredrik
    Fredrik avatar
    8 posts
    Member since:
    Sep 2014

    Posted 13 Sep 2014 Link to this post

    I'm currently converting an old data layer to use Data Access instead. One of the parts I'm porting over is an insert-or-update function. It seems AttachCopy is the way to go, and it does a great job either to update or insert. But the objects that are inserted doesn't seem to get their identity back during the operations (like they do if inserted with Add).

    Is there something I've missed or should I switch approach for the function? Thanks in advance!
  2. Answer
    Kaloyan Nikolov
    Kaloyan Nikolov avatar
    118 posts

    Posted 17 Sep 2014 Link to this post

    Hello Fredrik, 

    your approach should be perfectly valid. I suppose you miss to invoke the context.SaveChanges() method. It stores it actually to the DB and retrieves the Ids back in case they are autoinc. Also keep in mind that you should check the attached entity but not the original one (see the code below). 

    using (var dbContext = new EntitiesModel1())
        //This entity should be inserted
        var toAttach = new Entity1() { Name = "missing entity" };
        var attachedEntity = dbContext.AttachCopy(toAttach);
        //still the id is not retrieved back
        //now the Id should be updated

    I hope this helps. Should you have any additional questions do not hesitate to get back. 

    Kaloyan Nikolov
    OpenAccess ORM is now Telerik Data Access. For more information on the new names, please, check out the Telerik Product Map.
  3. Fredrik
    Fredrik avatar
    8 posts
    Member since:
    Sep 2014

    Posted 18 Sep 2014 in reply to Kaloyan Nikolov Link to this post

    Thanks! I had the SaveChanges() in place but had totally missed to actually use the attached entity returned from AttachCopy() instead of the original.
Back to Top