.net EntityFramework添加重复的子项

.net EntityFramework添加重复的子项,.net,entity-framework,.net,Entity Framework,事实上,我在弄清楚如何处理添加/更新复杂实体时遇到了巨大的问题,而子实体可能包含重复项(具有唯一键) 我试图将问题分解到核心: 三个实体:祖父1---*父亲*---*子女(1-多,多对多) 将出现一个异常,如“无法添加子项,因为索引IX_测试中存在重复项..” 我希望(当然)EF插入祖父+所有父亲+他们的关系,以及孩子+他们与父亲的关系 我尝试了很多不同的方法(例如在插入之前/之后对孩子们进行迭代和附加/分离),我甚至不能在这里列出它们 问题: 使其正常工作的最佳实践是什么?我几乎要放弃这一切,

事实上,我在弄清楚如何处理添加/更新复杂实体时遇到了巨大的问题,而子实体可能包含重复项(具有唯一键)

我试图将问题分解到核心:

三个实体:祖父1---*父亲*---*子女(1-多,多对多)

将出现一个异常,如“无法添加子项,因为索引IX_测试中存在重复项..”

我希望(当然)EF插入祖父+所有父亲+他们的关系,以及孩子+他们与父亲的关系

我尝试了很多不同的方法(例如在插入之前/之后对孩子们进行迭代和附加/分离),我甚至不能在这里列出它们

问题:

使其正常工作的最佳实践是什么?我几乎要放弃这一切,使用简单的SQL/或自己创建关系


谢谢你的时间和帮助

您遇到的问题是,您试图将现有实体添加到数据库中,因此会出现Id异常

我总是发现,首先处理与代码的多对多关系的最佳方法是创建映射实体(将生成映射表)

我的建议是创建一个父子实体:

public class FatherChild
{
    [Key]
    public int FatherId { get; set; }
    public virtual Father Father {get;set;}
    [Key]
    public int ChildId { get; set; }
    public virtual int Child { get; set; }
}
然后更新父类和子类:

public class Father
{
    [Key]
    public int ID { get; set; }

    public GrandFather RelatedFather;

    public ICollection<FatherChild> RelatedChildren { get; set; }
}

public class Child
{
    [Key]
    public int ID { get; set; }

    // assuming that you only navigate from one entity you only need this ICollection on Father or Child, not on both
    public ICollection<FatherChild> RelatedFathers { get; set; }
}
public class FatherChild
{
    [Key]
    public int FatherId { get; set; }
    public virtual Father Father {get;set;}
    [Key]
    public int ChildId { get; set; }
    public virtual int Child { get; set; }
}
public class Father
{
    [Key]
    public int ID { get; set; }

    public GrandFather RelatedFather;

    public ICollection<FatherChild> RelatedChildren { get; set; }
}

public class Child
{
    [Key]
    public int ID { get; set; }

    // assuming that you only navigate from one entity you only need this ICollection on Father or Child, not on both
    public ICollection<FatherChild> RelatedFathers { get; set; }
}
father.RelatedChildren.Add(fatherChild); //assuming that Father is your main entity and is the one holding the navigation property
// persist father in the db