I have 3 classes associated with 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 has one block. If I want to save Stat with the Entity Framework, I have to iterate through my "Quantities" list and check if there is already existing or recently created (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 that when more Quantities have the same block, an error occurs: "An object with the same key already exists in the ObjectStateManager. An ObjectStateManager cannot track multiple objects with the same key."
I have no idea how Stat can be updated along with a list of its quantities and units.
source share