SQLite-Net extensions: how to get rid of relationship records?
Let's say I have a many-to-many relationship like in the official example:
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 delete Student, the relationship record represented by the intermediate object is not deleted either. (And if I allow the cascading delete, the topic is deleted - which shouldn't happen.)
I am currently clearing it manually by deleting the entry with a custom query, but is there a better way with sqlite-net?
source to share
You can set to null
or empty the list property Subjects
and call UpdateWithChildren
on the student object.
student.Subjects = null;
conn.UpdateWithChildren(student);
It will update the student object and its relationship by deleting all entries for that student, which is equivalent to:
conn.Execute("DELETE FROM StudentSubject WHERE StudentId = ?", studentId);
The downside is that you have another "update" done on the database if you let SQLite-Net Extensions handle the relationship.
source to share