Andre Lashley
Andre Lashley

Reputation: 284

How do I clone an entity that has a client-generated GUID as its ID? (Model-first)

I am trying to clone a database record in the entity framework, but I am wondering how to account for ID fields in the object graph that are GUIDS which are not generated by SQL server.

I have tried a method I found here on stack overflow but the ID's were integers and didn't fit my use case (I got an exception when I tried it). I know that setting store generated pattern to Identity in the entity designer should in theory generate the GUID, but that option ends up giving me GUIDs that are all zeros. When I try to insert a second record, I get an exception regarding duplicate ID's.

What would be the best way to go about this?

Upvotes: 1

Views: 291

Answers (1)

marc_s
marc_s

Reputation: 754598

If you're cloning the existing row by inserting a new row into that same table, I would just replace the original row's GUID with a NEWID() value:

INSERT INTO dbo.SomeTable(ID, Col1, Col2, ...., ColN)
   SELECT
       NEWID(), -- get a new GUID for the new row
       Col1, Col2, ...., ColN
   FROM 
       dbo.SomeTable
   WHERE
       ID = (some value defined here)

You could wrap this into a stored procedure, e.g. CREATE PROCEDURE CloneSomeTableRow @SomeID UNIQUEIDENTIFIER and then call that from your Entity Framework context.

Upvotes: 1

Related Questions