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

问题描述 投票:3回答:2

我想要做的是复制/复制我的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);

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

await _db.AddAsync(item);

那么EF应该足够聪明,可以将该实体添加为新实体。然而,马上就发生了一个冲突,上面写着“id {schoolId}已经存在”并且不会插入。即使我重置了我想要添加的新项目的ID,我仍然会与学校iteam的关联/子项的ID发生冲突。

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

entity-framework-core deep-copy ef-core-2.0
2个回答
0
投票

我遇到了同样的问题,但在我的情况下,ef核心足够智能,即使使用现有ID也可以将它们保存为新实体。但是,在实现之前,我只是为所有项创建了一个复制构造函数,创建了一个只包含所需属性的本地任务变量并返回了副本。

Remove certain properties from object upon query EF Core 2.1


0
投票

我也有同样的问题,但在我的情况下,EF核心抛出异常“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; }
}

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

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

© www.soinside.com 2019 - 2024. All rights reserved.