c# - SQLite-Net Extensions how to correctly update object recursively -
i using sqlite-net pcl sqlite-net extensions development of application using xamarin.
i have 1 many relationship between 2 classes a
, b
defined follows:
public class { [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 father { get; set; } public b() { } public b(string name) { name = name; } }
what do, retrieve object of type a
database, remove 1 of sons
objects of type b
, update database accordingly. have tried:
var sons = new list<b> { new b("uno"), new b("due"), new b("tre"), }; 1 = new a("padre", sons); using (var conn = databasestore.getconnection()) { conn.deleteall<a>(); conn.deleteall<b>(); conn.insertwithchildren(one, true); 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); }
the problem both updatewithchildren
, insertorreplacewithchildren
the object not removed database, it's foreign key nulled. possible make delete son
object?
you're not trying delete object @ all. you're removing relationship between 2 objects, nothing stops having more objects related of them, deleting not correct may break other relationships.
it should more this:
using (var conn = databasestore.getconnection()) { var retrieved = conn.getwithchildren<a>(one.id); var due = retrieved.sons[1]; // not required if foreign key in other end, // usual way other scenario // retrieved.sons.remove(due); // conn.updatewithchildren(retrieved); // delete object if it's no longer required exist in database conn.delete(due); }
Comments
Post a Comment