簡體   English   中英

SQLite-Net Extensions如何正確地遞歸更新對象

[英]SQLite-Net Extensions how to correctly update object recursively

我正在使用SQLite-Net PCL和SQLite-Net擴展來使用Xamarin開發應用程序。

我在兩個類AB之間有一對多的關系,定義如下:

   public class A
{

    [PrimaryKey, AutoIncrement]
    public int Id
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

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

    public A()
    {
    }

    public A(string name, List<B> sons)
    {
        Name = name;
        Sons = sons;
    }

}

public class B
{

    [PrimaryKey, AutoIncrement]
    public int Id
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

    [ForeignKey(typeof(A))]
    public int FatherId
    {
        get;
        set;
    }

    [ManyToOne]
    public A Father
    {
        get;
        set;
    }

    public B()
    {
    }

    public B(string name)
    {
        Name = name;
    }

}

我想做的是從數據庫中檢索類型為A的對象,刪除類型為BSons對象之一,並相應地更新數據庫。 這是我嘗試過的:

        var sons = new List<B>
        {
            new B("uno"),
            new B("due"),
            new B("tre"),
        };

        one = new A("padre", sons);

        using (var conn = DatabaseStore.GetConnection())
        {
            conn.DeleteAll<A>();
            conn.DeleteAll<B>();

            conn.InsertWithChildren(one, true);

            A retrieved = conn.GetWithChildren<A>(one.Id);
            retrieved.Sons.RemoveAt(1);
        }

        using (var conn = DatabaseStore.GetConnection())
        {
            var retrieved = conn.GetWithChildren<A>(one.Id);
            retrieved.Sons.RemoveAt(1); //"due"

            //conn.UpdateWithChildren(retrieved);
            conn.InsertOrReplaceWithChildren(retrieved, true);
        }

問題在於,無論使用UpdateWithChildren還是使用InsertOrReplaceWithChildren ,該對象都不會真正從數據庫中刪除,而只是將其外鍵置為空。 是否可以刪除son對象?

您實際上並沒有嘗試刪除任何對象。 您只是刪除了兩個對象之間的關系,但是沒有什么阻止您擁有更多與它們相關的對象,因此刪除任何對象都是不正確的,因為您可能會破壞其他關系。

應該更像這樣:

using (var conn = DatabaseStore.GetConnection())
{
    var retrieved = conn.GetWithChildren<A>(one.Id);
    var due = retrieved.Sons[1];

    // This is not required if the foreign key is in the other end,
    // but it would be the usual way for any other scenario
    // retrieved.Sons.Remove(due);
    // conn.UpdateWithChildren(retrieved);

    // Then delete the object if it's no longer required to exist in the database
    conn.delete(due);
}

暫無
暫無

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

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