当我用其他外键更新对象中的子项时,我丢失了外键

I lose the foreign key when I update children in object with other foreign key

我正在使用 SQLite.NET-PCL 和 SQLiteNetExtensions

对象:

public class Object1
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set; }

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

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

public class Object2
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set; }

    [ForeignKey(typeof(Object1))]
    public int object1_id { get; set; }
    [ManyToOne]
    public Object1 Object1 { get; set; }

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

public class Object3
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set }
    public string name {get; set;}

    [ForeignKey(typeof(Object2))]
    public int object2_id { get; set; }
    [ManyToOne]
    public Object2 Object2 { get; set; }


    [ForeignKey(typeof(Object1))]
    public int object1_id { get; set; }
    [ManyToOne]
    public Object1 Object1 { get; set; }
}

"Insert Object1 - this works"

connection.Insert(Object1);

"Insert Object2s and UpdateWithChildren Object1 - this works"

        List<Object2> list_object2 = await API_query;
    List<Object2> Object2List = new List<Object2>();
    foreach (Object2 item in list_object2)
    {
         connection.Insert(item);
         Object2List.Add(item);
    }
    Object1.ListObject2 = Object2List;
    connection.UpdateWithChildren(Object1);

"Insert Object3s and UpdateWithChildren Object2 - this UpdateWithChildren works but too update Object2.object1_id to 0"

    List<Object3> list_object3 = await API_query
List<Object3> Object3List = new List<Object3>();
foreach (Object3 item in list_object3) 
{
    connection.Insert(item);
    Object3List.Add(item);
}
Object2.ListObject3 = Object3List;
connection.UpdateWithChildren(Object2);

当我用子对象更新 object2 时,Object2.object1_id 为 0,我丢失了 Object2.Object1_foreign_key 中的 Object1_foreign_key。

有什么想法吗?我的问题是什么?错误是什么?

我认为你的问题是这些行:

Object1.ListObject2 = Object2List;
connection.UpdateWithChildren(Object1);

正在正确设置外键,但是随后,您使用 Object2List:

的元素调用它
connection.UpdateWithChildren(Object2);

此时Object2null,因为没有设置逆关系,所以外键设置为0.

解决,如果不打算从Object2更新关系,可以设置Object1 -> Object2关系为ReadOnly:

[ManyToOne(ReadOnly = true)]
public Object1 Object1 { get; set; }

或者,您可以手动设置反向关系:

foreach (Object2 item in list_object2)
{
     connection.Insert(item);
     Object2List.Add(item);
     item.Object1 = Object1;
}

在第二次 UpdateWithChildren 之前,您必须将 Object1 设置为 Object2。

Object2.Object1 = Object1;

然后您可以执行第二个 UpdateWithChildren。

Object2.ListObject3 = Object3List;
connection.UpdateWithChildren(Object2);

如果你没有在更新前设置关系,你就会失去它。