Entity Framework 4.1 Codefirst: ошибка «Учитывая ограничения множественности» при удалении дочерних элементов «один ко многим»

У меня есть следующие классы в Entity Framework 4.1 (классы были сокращены, чтобы код оставался читабельным)

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 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 Machines { get; set; }
}

public class Machine : Hardware
{
    public Inventory Inventory { get; set; }
}

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity()
        .HasMany(mi => mi.MetaInformations).WithRequired(mi => mi.RelatedTo).WillCascadeOnDelete(true);
    modelBuilder.Entity()
            .HasMany(i => i.Machines).WithRequired(m => m.Inventory).WillCascadeOnDelete(true);

    base.OnModelCreating(modelBuilder);
}

В какой-то момент я хотел бы обновить машинная информация, поэтому, если она уже существует в базе данных, я загружаю ее, присоединяю, а затем очищаю предыдущие метаинформации, чтобы заменить их новыми.

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();
            //workingMachine.MetaInformations.ForEach(mi => { Dao.Db.MetaInformations.Attach(mi); Dao.Db.MetaInformations.Remove(mi); }); // tried this to, with variations
        }
        workingMachine.MetaInformations = m.MetaInformations;
    }
    DataContext.Dao.Db.SaveChanges();
}

Затем выдается следующее исключение DbUpdateException:

Связь из "MetaInformationObject_MetaInformations" AssociationSet находится в состоянии «Удалено». Учитывая множественность ограничений, соответствующий «MetaInformationObject_MetaInformations_Target» также должен быть в Состояние «Удалено».

Я попытался ответить на несколько вопросов здесь по SO, чтобы решить проблему, особенно пытаясь прочитать этот и ссылку , предоставленную в ответе (это причина почему есть прямая ссылка из MetaInformation на MetaInformationObject ), но я не могу понять, что не так.

8
задан Community 23 May 2017 в 11:59
поделиться