Reputation: 1271
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.
Upvotes: 4
Views: 2175
Reputation: 903
As you mentioned, the problem occurs when more than one quantity has same Unit. To avoid adding same unit multiple time you can check if a unit is already in the db. If it exists then reuse the existing unit.
if (q.Id == 0)
{
var unit=db.Units.FirstOrDefault(u=>u.Id==q.Unit.Id);
if(unit!=null)
q.Unit=unit;
db.Quantities.Add(q);
}
Upvotes: 1