在我的模型中,我有以下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 应用程序,用户可以在其中编辑这些内容,包括添加和删除Section
s 和SectionStep
s。数据通过 JSON 发布到服务器,服务器正确读取并添加所有内容。但是,当我将两个SectionStep
s 添加到同一部分时,我收到以下错误:
ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。
POST 到服务器的 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
以相同的方式处理 s,并且添加两个Section
s 就可以了。