Search code examples
c#databasesqlitemany-to-manysqlite-net-extensions

Many to Many "self"-relation SQLite: is it possible?



I'm using SQLite.net and SQLite-Net Extensions. I would like to create a many to many self-relation.
In my case I have a child class with some siblings, of course the siblings are still of child type. Therefore I tried to implement a manytomany relation:

Child Class

[ManyToMany(typeof(Brotherhood), CascadeOperations = CascadeOperation.All)]
public List<Child> Siblings_DB { get; set; }

Brotherhood Class

class Brotherhood
{
    [ForeignKey(typeof(Child))]
    public int ID_child1 { get; set; }

    [ForeignKey(typeof(Child))]
    public int ID_child2 { get; set; }

}

That should be all the work.
Then I create a Child and add a sibling in the Siblings list, but when I try to save the class in the DB using InsertOrReplaceWithChildren(Child,true) only ID_child1 is updated and ID_child2 stay to 0.
Any idea? What am I doing wrong?
Alex


Solution

  • After some attempts I managed in realising the many to many self relation, I was just a bit confused on having two manytomany relation in the same class: I was wondering which was the "official" one. Eventually I understood that both were! And the sum of the siblings was the sum of the two Lists.

    [ManyToMany(typeof(Brotherhood), "ChildID1", "Siblings_DB_support", CascadeOperations = CascadeOperation.All)]
    public List<Child> Siblings_DB { get; set; }
    [ManyToMany(typeof(Brotherhood), "ChildID2", "Siblings_DB", CascadeOperations = CascadeOperation.All)]
    public List<Child> Siblings_DB_support { get; set; }
    

    And the relationship table:

    public class Brotherhood
    {
        [ForeignKey(typeof(Child))]
        public int ChildID1 { get; set; }
    
        [ForeignKey(typeof(Child))]
        public int ChildID2 { get; set; }
    }