向实体框架中的List添加两个新元素

时间:2013-08-19 21:17:37

标签: asp.net-mvc entity-framework

在我的模型中,我有以下Section类:

public partial class Section
{
    public Section()
    {
        Steps = new List<SectionStep>();
    }

    public int Id { get; set; }
    public int SortId { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Html { get; set; }
    public Nullable<int> Tutorial_Id { get; set; }
    [JsonIgnore]
    public virtual Tutorial Tutorial { get; set; }
    public virtual ICollection<SectionStep> Steps { get; set; }
    [NotMapped]
    public bool _destroy { get; set; }
}

以及以下SectionStep类:

public class SectionStep
{
    public int Id { get; set; }
    public int SortId { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Html { get; set; }

    [JsonIgnore]
    public virtual Section Section { get; set; }

    [NotMapped]
    public bool _destroy { get; set; }
}

我有一个ASP.NET应用程序,用户可以在其中编辑这些内容,包括添加和删除SectionSectionStep。数据通过JSON发布到服务器,服务器正确读取并添加一切正常。但是,当我向同一部分添加两个SectionStep时,我收到以下错误:

  

ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法使用相同的键跟踪多个对象。

发布到服务器的JSON被反序列化为List<Section> sections以下代码处理此问题并将适当的对象添加到我的实体模型中。

        foreach (Section section in sections)
            {                    
                if (section._destroy)
                {
                    // if id is 0, it was never even added
                    if (section.Id > 0)
                        db.Entry(section).State = EntityState.Deleted;
                }
                else if (section.Id == 0)
                {
                    db.Entry(section).State = EntityState.Added;
                }
                else
                {
                    db.Entry(section).State = EntityState.Modified;
                }
                foreach (SectionStep step in section.Steps.ToList())
                {                        
                    if (step._destroy)
                    {
                        // if id is 0, it was never even added so don't delete
                        if (step.Id > 0)
                            db.Entry(step).State = EntityState.Deleted;
                        else
                            section.Steps.Remove(step);
                    }
                    else if (step.Id == 0)
                    {
                        db.Entry(step).State = EntityState.Added;
                        db.SaveChanges();
                    }
                    else
                    {
                        db.Entry(step).State = EntityState.Modified;
                    }
                }
            }
            db.SaveChanges();
            returnSections.AddRange(db.Sections.Where(s => s.Tutorial_Id == tutorial_id).OrderBy(s => s.SortId).ToArray());

在我看来,问题是当我添加两个步骤时,由于某种原因它们都具有相同的Id。起初他们确实以Id = 0开头,因为我让数据库自动分配,但是我以相同的方式处理Section,并且添加两个Section就可以了。

0 个答案:

没有答案