0

I'm trying to do a copy of an object in ef-core 2.0. Im using a query that fetches a lot of objects with Include ande then I use the AsNoTracking to tell ef that this is a completly new object.

Im using the default settings and I'm letting the database generate the Ids on insert. But when I use the AsNoTracking-query I still get the id of the original object which gives me an exception on SaveChanges.

SqlException: Cannot insert explicit value for identity column in table 'Plans' when IDENTITY_INSERT is set to OFF.

I dont actually want to change this setting and if i traverse the objects and changes the Id to 0 it works. Is there any way to handle this problem without traversing all the objects?

Is there a better way to do create a copy?

forsmyr
  • 304
  • 3
  • 14
  • 2
    Similar to https://stackoverflow.com/questions/49378462/replicate-entire-row-in-entity-framework-core. And no better way AFAIK. – Ivan Stoev May 02 '18 at 09:15

1 Answers1

0

As Ivan comments above there is no better answer than that so check this link out for a better answer. In my case I get the object and the hierarchy in the same way as before then traverse the objects and sets the PK to 0.

Replicate Entire Row In Entity Framework Core

forsmyr
  • 304
  • 3
  • 14