Frage

Ich habe folgende Klasse:

public class Application
{
    public int Id { get; set; }

    /* Other properties */

    public int LegacyId { get; set; }
    public int LegacyParentId { get; set; }

    public int? ApplicationSupersessionId { get; set; }
    public virtual ICollection<Application> ApplicationSupersessions { get; set; }

    public Application()
    {
        ApplicationSupersessions = new List<Application>();
    }
}

Wo ApplicationSupersessions ist eine optionale selbstverbundene Entität.Ich habe bereits Daten zu meinem hinzugefügt Applications tabelle und ich versuche, die Daten anzupassen, die derzeit so aussehen:

enter image description here

Aber ich brauche Bewerbungen 5413 und 5414 um eine zu haben ApplicationSupersessionId von 5415 so sieht es in unserem Altsystem aus, Deshalb habe ich das hinzugefügt 2 Legacy Spalten

Also habe ich Folgendes versucht:

var applications = CatalogueContext.Applications.ToList();

foreach (var application in applications)
{
    var legacyChildren = applications.Where(x => 
        x.LegacyParentId == application.LegacyId).ToList();

    if(legacyChildren.Any())
    {
        foreach(var child in legacyChildren)
        {
            application.ApplicationSupersessions.Add(child);
        }

       CatalogueContext.Entry(application).State = EntityState.Modified;
    }
}

CatalogueContext.SaveChanges();

Aber ich bekomme den folgenden Fehler in der Zeile CatalogueContext.Entry(application).State = EntityState.Modified;:

enter image description here

War es hilfreich?

Lösung

Ich habe es geschafft, das zu lösen.Ich hatte die Beziehung in meiner Konfiguration falsch eingerichtet.

Ich hatte das:

HasOptional(x => x.ApplicationSupersessions)
    .WithMany()
    .HasForeignKey(x => x.ApplicationSupersessionId)
    .WillCascadeOnDelete(false);

Wenn es das hätte sein sollen:

HasMany(x => x.ApplicationSupersessions)
    .WithOptional()
    .HasForeignKey(x => x.ApplicationSupersessionId)
    .WillCascadeOnDelete(false);

Ich bin mir nicht sicher, was der Unterschied ist und ob es sich um einen EF-Fehler handelt oder nicht?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top