简体   繁体   English

从现有记录中复制带有新键的新记录

[英]Copy a new record with new key from existing record

Have many tables where I have GUID as primary key in each table.有很多表,我在每个表中都有 GUID 作为主键。 I want to create a copy with new Guid from the original record in all tables.我想从所有表的原始记录中创建一个带有新 Guid 的副本。

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.执行此操作时,我收到错误消息“Guid”属性是对象的关键信息的一部分,无法在第 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.         }

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.如果要克隆一个实体并且该实体的 PK 是一个 Identity 列,那么最简单的方法是将其分离,然后将其添加到 DbContext。 (rather than Attaching) The DbContext will treat it as a new, untracked entity and assign it a new ID: (而不是附加)DbContext 会将其视为一个新的、未跟踪的实体并为其分配一个新 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.这可能看起来有点奇怪,但 AsNoTracking() 告诉 DbContext 不要跟踪正在加载的实体。 When you add a Project with an Identity column, that column is ignored and a new ID will be assigned.当您添加具有标识列的项目时,该列将被忽略,并将分配一个新 ID。 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.如果您不使用标识列,那么您只需将项目的 ID 设置为新值,然后再将其添加到 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.请注意,在为 PK/FK 使用 GUID 时,我建议使用使用顺序 UUID 算法的标识列,例如 SQL Server 中的 NewSequentialId()。 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.即使在代码中设置这些,您也可以找到如何生成合适的 UUID 的字节序可排序变体的示例,这可以为您节省大量的索引性能/存储大小问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM