I have the following classes in Entity Framework 4.1 (classes were cropped to read code)
public class MetaInformation { public int Id { get; set; } public virtual MetaInformationObject RelatedTo { get; set; } } public abstract class MetaInformationObject { public int Id { get; set; } public virtual List<MetaInformation> MetaInformations { get; set; } } [Table("Hardwares")] public class Hardware : MetaInformationObject { [MaxLength(100)] public string Name { get; set; } } public class Inventory { public int Id { get; set; } public virtual List<Machine> Machines { get; set; } } public class Machine : Hardware { public Inventory Inventory { get; set; } } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Isis.Business.Base.MetaInformationObject>() .HasMany<Isis.Business.Base.MetaInformation>(mi => mi.MetaInformations).WithRequired(mi => mi.RelatedTo).WillCascadeOnDelete(true); modelBuilder.Entity<Isis.Business.Inventory.Inventory>() .HasMany<Isis.Business.Inventory.Machine>(i => i.Machines).WithRequired(m => m.Inventory).WillCascadeOnDelete(true); base.OnModelCreating(modelBuilder); }
At some point, I would like to update the information about the machine, so if it already exists in the database, I load it, attach it, and then clear the previous meta information to replace it with new ones.
public void UpdateMachine(Inventory i, Machine m) { DataContext.Dao.Db.Inventories.Attach(i); if (!i.Machines.Exists(InnerHardware => InnerHardware.SerialNumber == m.SerialNumber)) { i.Machines.Add(m); } else { var workingMachine = i.Machines.First(Machine => Machine.SerialNumber == m.SerialNumber); Dao.Db.Machines.Attach(workingMachine); if (workingMachine.MetaInformations != null && workingMachine.MetaInformations.Count > 0) { workingMachine.MetaInformations.Clear();
And then the following DbUpdateException is thrown:
Relations from 'MetaInformationObject_MetaInformations' AssociationSet is in the Deleted state. Given the multiplicity of constraints corresponding to 'MetaInformationObject_MetaInformations_Target' should also be in the Deleted State.
I tried to answer some questions here to solve the problem, especially trying to read this and the link provided in the answer (which is the reason there is a direct link from MetaInformation to MetaInformationObject ), but I can not understand what is wrong.
source share