Search code examples
c#sqlitesqlite-netsqlite-net-extensions

fully delete a relationship in a many to many table in sqlite-net extension?


I have a similar situation, to this post the delete works but only on students and classes table, in the student_classes table the elements are not deleted.

  public class Students
{
    [PrimaryKey, AutoIncrement]
    public int StudentId { get; set; }
    public string Name { get; set; }

    [ManyToMany(typeof(Students_Classes))]
    public List<Classes> Classes { get; set; }
}

public class Classes
{
    [PrimaryKey, AutoIncrement]
    public int ClassId { get; set; }
    public string Name { get; set; }

    [ManyToMany(typeof(Students_Classes))]
    public List<Students> Students { get; set; }
}

public class Students_Classes
{
   [PrimaryKey, AutoIncrement]
    public int StudentClassesId { get; set; }

    [ForeignKey(typeof(Students))]
    public int StudentFId { get; set; }

    [ForeignKey(typeof(Classes))]
    public int ClassFId { get; set; }
}

To delete I use the following code

conn.Delete(student, true);

I have no problem during insert and updates thanks

p.s. My classes have different names, but doesn't matter, the code is really identical


Solution

  • Cascade deletion doesn't remove intermediate records. These records are harmless, but completely useless, you can remove them manually. For example:

    // Fetch IDs of intermediate records to delete
    var deleteIds = conn.Table<Student_Classes>()
        .Where(e => e.StudentFId == student.StudentId)
        .Select(e => e.StudentFId).ToList();
    
    // Perform batch deletion
    conn.DeleteAllIds<Student_Classes>(deleteIds);
    

    Or more performant (but less refactor friendly):

    var deleteQuery = "DELETE FROM Student_Classes WHERE StudentFId == ?";
    conn.Execute(deleteQuery, student.StudentId);