我正在使用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; }
}
“插入Object1 - 这可行”
connection.Insert(Object1);
“插入Object2s和UpdateWithChildren Object1 - 这可行”
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);
“插入Object3s和UpdateWithChildren Object2 - 此UpdateWithChildren可以工作,但也将Object2.object1_id更新为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。
有什么想法吗?什么是我的问题?什么是错误?
答案 0 :(得分:1)
我认为你的问题是这些问题:
Object1.ListObject2 = Object2List;
connection.UpdateWithChildren(Object1);
正确设置外键,但是,您使用Object2List
元素调用它:
connection.UpdateWithChildren(Object2);
此时,Object2
为null
,因为没有设置反向关系,因此外键设置为0
。
要解决此问题,如果您不打算从Object2更新关系,则可以设置Object1 - &gt; 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;
}
答案 1 :(得分:0)
在第二个UpdateWithChildren之前,您必须将Object1设置为Object2。
Object2.Object1 = Object1;
然后你可以做第二个UpdateWithChildren。
Object2.ListObject3 = Object3List;
connection.UpdateWithChildren(Object2);
如果您在更新前没有设置关系,则会丢失它。