簡體   English   中英

SQLite.Net擴展-更新時刪除子級

[英]SQLite.Net Extensions - Delete Children on Update

我有以下兩個課程。 當我保存一個包含多個項目(B)的A時,我得到了預期的結果。 但是,當我保存對A的更改(例如,一個空的Items(B)列表)時,我希望表B中的所有元素會自動刪除,因為它們在任何地方都沒有被引用(無意單獨查詢)。 而是將表中每個項目的外鍵(IDofA)設置為Null。 在我的情況下,這導致表(B)不斷增長,因為A的某些對象從未刪除過,只是更新過。

public class A
{
    public string Name{ get; set; }

    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<B> Items { get; set; }
}

public class B
{
    [ForeignKey(typeof(A))]
    public string IDofA { get; set; }
}


//This is the Generic Save Method that I use for all the Objects
public virtual void Save(T element)
    {
        CreateID(element);
        if (!RuntimeCache.Any(x => x.ID == element.ID))
        {
            RuntimeCache.Add(element);
        }

        element.UpdateChangeDate();

        RunDBQueryAsync((conn) =>
        {
            conn.InsertOrReplaceWithChildren(element);
        });
    }

更新元素永遠不會導致設計刪除子對象。 僅通過更新另一個表來執行破壞性操作不是一個好主意。 您可以通過刪除不再引用的元素來解決您不斷增長的表格問題:

public virtual void Save(T element)
{
    CreateID(element);
    if (!RuntimeCache.Any(x => x.ID == element.ID))
    {
        RuntimeCache.Add(element);
    }

    element.UpdateChangeDate();

    RunDBQueryAsync((conn) =>
    {
        conn.InsertOrReplaceWithChildren(element);
        // Delete orphaned children
        conn.Execute("DELETE FROM B WHERE IDofA IS NULL');
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM