I have 3 classes, related to 3 database tables:
public class Stat
{
public int Id { get; set; }
public string Name { get; set; }
public List<Quantity> Quantities { get; set; }
}
public class Quantity
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Stat Stat { get; set; }
public virtual Unit Unit { get; set; }
}
public class Unit
{
public int Id { get; set; }
public string Name { get; set; }
public string Abbreviation { get; set; }
public List<Quantity> Quantities { get; set; }
}
A Stat can have a list of Quantities, and a Quantity have one Unit. If I want to save a Stat with Entity Framework, I have to iterate through its list of Quantities, and check if the Quantity already exists, or newly created (the data comes from an HTML Form).
public void UpdateStat(Stat stat)
{
foreach (Quantity q in stat.Quantities)
{
if (q.Id == 0)
{
db.Quantities.Add(q);
}
else
{
db.Entry(q).State = EntityState.Modified;
}
}
db.Entry(stat).State = EntityState.Modified;
db.SaveChanges();
}
The problem is, when more Quantities have the same Unit, an error occurs: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."
I have no idea, how a Stat can be updated with the list of its Quantities and Units together.
statattached to the context? If so you do not need to add the entities individually, simply having them in the Quantities collection of stat will apply the appropriate operation.