EF Core多導航屬性產生循環依賴

entity-framework-core

我有以下映射配置:

入門級:

entity
    .HasOne(e => e.CurrentHandling)
    .WithOne()
    .HasForeignKey<Entry>(e => e.CurrentHandlingID)
    ;

entity
    .HasMany(e => e.Handlings)
    .WithOne(h => h.Entry)
    .HasForeignKey(h => h.EntryID)
    ;

處理級:

entity
    .HasOne(h => h.Entry)
    .WithMany(e => e.Handlings)
    .HasForeignKey(h => h.EntryID)
        .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);

ERM: 在此處輸入圖像描述

當我嘗試保存上下文時,我得到以下異常:

System.InvalidOperationException:'無法保存更改,因為在要保存的數據中檢測到循環依賴關係:'ForeignKey:Entry.CurrentHandlingID - > Handling.HandlingID唯一ToPrincipal:CurrentHandling,ForeignKey:Handling.EntryID - > Entry.EntryID ToDependent:處理ToPrincipal:進入'。'

測試數據:

errorRepo.EnableBulkModus();

var handling = errorRepo.AddHandling(new Handling {
     CorrectedMessage = "correct",
     HandlingStatusID = 7,
     Updated = DateTime.UtcNow,
     UpdatedBy = nameof(DbInitializer)
});

var reference = errorRepo.AddReference(new Reference {
    ForeignKeyTypeID = 4,
    ForeignKeyValue = "42",
    Name = "SystemB",
    ReferenceTypeID = 6
});

var entry = errorRepo.AddEntry(new Entry {
    CurrentHandling = handling,
    DisplayMessage = "Wrong!",
    ErrorMessage = "error!",
    Inserted = DateTime.UtcNow.AddMinutes(-5),
    OriginalMessage = "incorrect",
    InsertedBy = nameof(DbInitializer),
    UUID = Guid.NewGuid(),
    Reference = reference,
    StatusID = 5
});

handling.Entry = entry;
entry.Handlings.Add(handling);

errorRepo.DisableBulkModus(true);

errorRepo.EnableBulkModus();設置一個標誌,表示調用CommitChanges()時存儲庫不保存CommitChanges()errorRepo.DisableBulkModus(true);相同errorRepo.DisableBulkModus(true); ,它將標誌設置為false。布爾表示存儲庫應該執行CommitChanges()

如何更改映射以避免循環依賴?

親切的問候。

編輯(11.03.2017)

我從Handling-Class中刪除了映射,並在Entry-Class中添加了.OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict)行:

    entity
        .HasMany(e => e.Handlings)
        .WithOne(h => h.Entry)
        .HasForeignKey(h => h.EntryID)
        .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict)
        ;

相同的例外:

System.InvalidOperationException:'無法保存更改,因為在要保存的數據中檢測到循環依賴關係:'ForeignKey:Entry.CurrentHandlingID - > Handling.HandlingID唯一ToPrincipal:CurrentHandling,ForeignKey:Handling.EntryID - > Entry.EntryID ToDependent:處理ToPrincipal:進入'。'

一般承認的答案

看到這個:

// 1.
var entry = errorRepo.AddEntry(new Entry {
    CurrentHandling = handling,
    ...
});
...
// 2.
handling.Entry = entry;

下面的代碼1.要求entry接收handling的主鍵作為外鍵。下面的代碼2.需要handling以將entry的主鍵作為FK:雞和雞蛋問題。

由於handling依賴於entry (因為1-0..1關係),因此應首先插入entry尚未設置其CurrentHandling屬性。然後保存更改,因此entry知道其生成的PK。然後設置entry.CurrentHandlinghandling.Entry並再次保存更改。

您可能希望將此代碼包裝在事務中。

順便說一句,行entry.Handlings.Add(handling);是多餘的。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow