Home > Back-end >  Copy a new record with new key from existing record
Copy a new record with new key from existing record

Time:07-13

Have many tables where I have GUID as primary key in each table. I want to create a copy with new Guid from the original record in all tables.

While doing this, I am getting an error The property 'Guid' is part of the object's key information and cannot be modified in line# 9.

1. var project = context.Projects.FirstOrDefault(x => x.Guid == projectGuid);  // existing record
2.           if (project != null)
3.            {
4.            project.Guid = Guid.NewGuid(); // Setting newguid
5.          //....... need same values from rest of the columns
6.
7.            project.CreatedBy = userAccountGuid;
8.            project.CreatedDate = DateTime.Now;
9.            context.Projects.Add(project);   // Adding a new record
10.
11.         }

CodePudding user response:

If you want to clone an entity and that entity's PK is an Identity column, then the easiest way to do that is to detach it, then add it to the DbContext. (rather than Attaching) The DbContext will treat it as a new, untracked entity and assign it a new ID:

var project = context.Projects.AsNoTracking().FirstOrDefault(x => x.Guid == projectGuid);
if (project != null)
    context.Projects.Add(project);

This may look a bit odd, but AsNoTracking() tells the DbContext not to track the entity being loaded. When you add a Project with an Identity column, that column is ignored and a new ID will be assigned. If you aren't using an identity column then you can then just set the project's ID to a new value before adding it to the DbSet.

if (project != null)
{
    project.Id = Guid.NewGuid();
    context.Projects.Add(project);
}

Note that when using GUIDs for PKs/FKs, I would recommend using identity columns using a sequential UUID algorithm such as NewSequentialId() in SQL Server. Even if setting these in code you can find examples of how to generate a suitable endian-sortable variation of the UUID which can save you a lot of performance/storage size pain with indexing.

  • Related