实体框架6克隆父数据库和数据库中的所有子项

时间:2016-09-30 13:26:57

标签: c# asp.net-mvc entity-framework entity-framework-6 clone

我正在尝试复制一个对象(Parent)及其关系(Children1,Children2,Children3和Children4),在数据库中为每个对象创建一个新的id,但它仍然失败。有没有办法可以做到这一点?

以下是对象的结构及其关系。拜托,我需要很多帮助我的人。

public class Parent
{
    [PrimaryKey]
    public long IdParent {get; set;}
    public string Description {get; set;}
    public string OtherValue {get; set;}

    public virtual ICollection<Children1> Childrens1 {get; set;}
}

public class Children1
{
    [PrimaryKey]
    public long IdParent {get; set;}
    [PrimaryKey]
    public long IdChildren1 {get; set;}
    public string Description {get; set;}

    public virtual Parent Parent {get; set;}
    public virtual ICollection<Children1> Childrens1 {get; set;}
}

public class Children2
{
    [PrimaryKey]
    public long IdParent {get; set;}
    [PrimaryKey]
    public long IdChildren1 {get; set;}
    [PrimaryKey]
    public long IdChildren2 {get; set;}
    public string Description {get; set;}

    public virtual Children1 Children1 {get; set;}
}

public class Children3
{
    [PrimaryKey]
    public long IdParent {get; set;}
    [PrimaryKey]
    public long IdChildren1 {get; set;}
    [PrimaryKey]
    public long IdChildren3 {get; set;}
    public string Description {get; set;}

    public virtual Children1 Children1 {get; set;}
    public virtual ICollection<Children4> Childrens4 {get; set;}
}

public class Children3
{
    [PrimaryKey]
    public long IdParent {get; set;}
    [PrimaryKey]
    public long IdChildren1 {get; set;}
    [PrimaryKey]
    public long IdChildren3 {get; set;}
    [PrimaryKey]
    public long IdChildren4 {get; set;}
    public string Description {get; set;}

    public virtual Children3 Children3 {get; set;}
}

enter image description here

2 个答案:

答案 0 :(得分:0)

在这种情况下最好的做法是将对象从上下文中分离然后重新插入它,但这种方法的唯一问题是分离父对象不会分离相关对象,你必须明确地分离所有相对对象然后重新插入它们来制作它们的克隆

context.Detach(object);
context.SaveChanges(object);
context.Entry(object).State = EntityState.Added;
context.SaveChanges();

答案 1 :(得分:0)

这就是我接近这个的方法。从没有跟踪的上下文中检索所有父子项,并将它们添加回上下文以进行克隆。

(我只是根据您的实体图显示示例代码,因为您的实体模型类与它不匹配。)

public Item DeepClone(Parent item)
{
    Parent itemClone = db.Parents
        .Include(i => i.Childrens1.Select(c => c.Childrens2 ))
        .Include(i => i.Childrens3.Select(c => c.Childrens4 ))
        .AsNoTracking()
        .FirstOrDefault(i => i.IdParent == item.IdParent);

    db.Items.Add(itemClone);
    db.SaveChanges();
    return itemClone;
}