Search code examples
sqlite-netsqlite-net-extensions

SQLite-Net Extensions: How to get rid of relationship records?


Let's say I have a many-to-many relationship like in the official sample:

public class Student
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Name { get; set; }

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

public class Subject
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Description { get; set; }

    [ManyToMany(typeof(StudentSubject))]
    public List<Subject> Subjects { get; set; } 
}

public class StudentSubject
{
    [ForeignKey(typeof(Student))]
    public int StudentId { get; set; }

    [ForeignKey(typeof(Subject))]
    public int SubjectId { get; set; }
}

If I am now deleting a Student, the relationship record represented by the intermediate object does not get deleted, too. (And if I am enabling cascading deletion, the Subject gets deleted – what should not happen.)

Currently I am cleaning up manually by deleting the record with a custom query, but is there a better way with sqlite-net?


Solution

  • You can set to null or an empty list the Subjects property and call UpdateWithChildren on the student object.

    student.Subjects = null;
    conn.UpdateWithChildren(student);
    

    It will update the student object and its relationships, deleting all the records for that student, which is equivalent to:

    conn.Execute("DELETE FROM StudentSubject WHERE StudentId = ?", studentId);
    

    The drawback is that you have one more 'update' statement executing in the database if you let SQLite-Net Extensions handle the relationship.