SQLite-Net 扩展:如何摆脱关系记录?

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

假设我有一个像官方示例中那样的多对多关系:

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; }
}

如果我现在删除一个学生,中间对象代表的关系记录也不会被删除。 (如果我启用级联删除,主题将被删除——这是不应该发生的。)

目前我正在通过使用自定义查询删除记录来手动清理,但是使用 sqlite-net 有更好的方法吗?

您可以将 null 或空列表设置为 Subjects 属性 并在学生对象上调用 UpdateWithChildren

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

它将更新学生对象及其关系,删除该学生的所有记录,相当于:

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

缺点是,如果您让 SQLite-Net Extensions 处理关系,您将在数据库中多执行一个 'update' 语句。