This is a migrated thread and some comments may be shown as answers.

AttachCopy and identities for inserted entities

2 Answers 62 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Fredrik
Top achievements
Rank 2
Fredrik asked on 13 Sep 2014, 03:27 PM
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 Answers, 1 is accepted

Sort by
0
Accepted
Kaloyan Nikolov
Telerik team
answered on 17 Sep 2014, 05:23 PM
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
    Console.WriteLine(attachedEntity.Id);
 
    dbContext.SaveChanges();
     
    //now the Id should be updated
    Console.WriteLine(attachedEntity.Id);
}


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


Regards,
Kaloyan Nikolov
Telerik
 
OpenAccess ORM is now Telerik Data Access. For more information on the new names, please, check out the Telerik Product Map.
 
0
Fredrik
Top achievements
Rank 2
answered on 18 Sep 2014, 04:45 PM
Thanks! I had the SaveChanges() in place but had totally missed to actually use the attached entity returned from AttachCopy() instead of the original.
Tags
Development (API, general questions)
Asked by
Fredrik
Top achievements
Rank 2
Answers by
Kaloyan Nikolov
Telerik team
Fredrik
Top achievements
Rank 2
Share this question
or