1

Xamarin を使用してアプリケーションを開発するために、SQLite-Net PCL を SQLite-Net 拡張機能と共に使用しています。

2 つのクラス間に 1 対多の関係があり、次のよう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;
    }

}

私がしたいのは、データベースからタイプのオブジェクトを取得し、タイプのオブジェクトのA1つを削除して、それに応じてデータベースを更新することです。これは私が試したことです:SonsB

        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);
        }

問題はUpdateWithChildrenInsertOrReplaceWithChildrenオブジェクトの有無にかかわらず、実際にはデータベースから削除されず、外部キーが null になっていることだけです。sonオブジェクトを削除させることはできますか?

4

1 に答える 1

2

オブジェクトをまったく削除しようとしているわけではありません。2 つのオブジェクト間の関係を削除しているだけですが、それらのいずれかに関連するオブジェクトが増えることを妨げるものは何もないため、他の関係を壊す可能性があるため、いずれかを削除することは正しくありません。

次のようになります。

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);
}
于 2015-03-17T09:16:59.133 に答える