ASP.NET MVC with Entity Framework - updating / saving complex type properties

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.

+4
source share
1 answer

As you already mentioned, the problem occurs when more than one quantity has the same Unit. To avoid adding the same element several times, you can check if the device is in db. If it exists, reuse the existing device.

 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); } 
+1
source

Source: https://habr.com/ru/post/1495135/


All Articles