简体   繁体   English

SQLite.Net扩展-更新时删除子级

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

I have the following two Classes. 我有以下两个课程。 When I Save A with multiple Items (B) in it, I get the expected result. 当我保存一个包含多个项目(B)的A时,我得到了预期的结果。 But when I save changes to A, such as an empty List of Items(B) I would expect that all elements in table B automatically get deleted because they are not referenced anywhere (Query them separately is not intented). 但是,当我保存对A的更改(例如,一个空的Items(B)列表)时,我希望表B中的所有元素会自动删除,因为它们在任何地方都没有被引用(无意单独查询)。 Instead the Foreign Key(IDofA) of every item is set to Null in the table. 而是将表中每个项目的外键(IDofA)设置为Null。 In my case this is leading to an endless growing Table (B) because some Objects of A are never deleted, just updated. 在我的情况下,这导致表(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);
        });
    }

Updating an element will never result in deleting children objects by design. 更新元素永远不会导致设计删除子对象。 Performing destructive operations on a table just by updating another is not a good idea. 仅通过更新另一个表来执行破坏性操作不是一个好主意。 Your endless growing table problem can be solved just by deleting elements that are not referenced anymore: 您可以通过删除不再引用的元素来解决您不断增长的表格问题:

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