如何在 EF Core 中进行深度克隆/复制

tan*_*a_s 7 deep-copy entity-framework-core ef-core-2.0

我想做的是School在 EF Core 中复制/复制我的对象及其所有子项/关联

我有如下内容:

var item = await _db.School
.AsNoTracking()
.Include(x => x.Students)
.Include(x => x.Teachers)
.Include(x => x.StudentClasses)
.ThenInclude(x => x.Class)
.FirstOrDefaultAsync(x => x.Id == schoolId);
Run Code Online (Sandbox Code Playgroud)

我一直在阅读深度克隆,似乎我应该能够只添加实体......所以几乎是下一行。

await _db.AddAsync(item);
Run Code Online (Sandbox Code Playgroud)

然后 EF 应该足够聪明,可以将该实体添加为新实体。但是,马上我就遇到了一个冲突,说“id {schoolId} 已经存在”并且不会插入。即使我重置了我尝试添加的新项目的 Id,我仍然会与学校 itam 的协会/孩子的 Id 发生冲突。

有没有人熟悉这个以及我可能做错了什么?

Tim*_*thy 1

我也遇到了同样的问题,但就我而言,EF core 抛出异常“id 已存在”。按照@Irikos的回答,我创建了克隆我的对象的方法。

这是例子

public class Parent
{
    public int Id { get; set; }
    public string SomeProperty { get; set; }
    public virtual List<Child> Templates { get; set; }

    public Parent Clone()
    {
        var output = new Parent() { SomeProperty = SomeProperty };

        CloneTemplates(output);

        return output;
    }

    private void CloneTemplates(Parent parentTo, Child oldTemplate = null, Child newTemplate = null)
    {
        //find old related Child elements
        var templates = Templates.Where(c => c.Template == oldTemplate);

        foreach (var template in templates)
        {
            var newEntity = new Child()
            {
                SomeChildProperty = template.SomeChildProperty,
                Template = newTemplate,
                Parent = parentTo
            };

            //find recursivly all related Child elements
            CloneTemplates(parentTo, template, newEntity);

            parentTo.Templates.Add(newEntity);
        }
    }
}

public class Child
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public virtual Parent Parent { get; set; }
    public int? TemplateId { get; set; }
    public virtual Child Template { get; set; }
    public string SomeChildProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我就DbContext.Parents.Add(newEntity)打电话DbContext.SaveChanges()

这对我有用。也许这对某人有用。