Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy records from between two databases using EF

I need to copy data from one database to another with EF. E.g. I have the following table relations: Forms->FormVersions->FormLayouts... We have different forms in both databases and we want to collect them to one DB. Basically I want to load Form object recursively from one DB and save it to another DB with all his references. Also I need to change IDs of the object and related objects if there are exists objects with the same ID in the second database.

Until now I have following code:

Form form = null;
using (var context = new FormEntities())
        {
            form = (from f in context.Forms
                        join fv in context.FormVersions on f.ID equals fv.FormID
                        where f.ID == 56
                        select f).First();
        }

        var context1 = new FormEntities("name=FormEntities1");
        context1.AddObject("Forms", form);
        context1.SaveChanges();

I'm receiving the error: "The EntityKey property can only be set when the current value of the property is null."

Can you help with implementation?

like image 832
zosim Avatar asked Apr 22 '26 19:04

zosim


1 Answers

The simplest solution would be create copy of your Form (new object) and add that new object. Otherwise you can try:

  1. Call context.Detach(form)
  2. Set form's EntityKey to null
  3. Call context1.AddObject(form)
like image 78
Ladislav Mrnka Avatar answered Apr 25 '26 11:04

Ladislav Mrnka