【问题标题】:SQLite-Net Extensions: How to get rid of relationship records?SQLite-Net Extensions:如何摆脱关系记录?
【发布时间】:2015-04-18 01:41:40
【问题描述】:

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

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 有更好的方法吗?

【问题讨论】:

    标签: sqlite-net sqlite-net-extensions


    【解决方案1】:

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

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

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

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

    缺点是如果您让 SQLite-Net Extensions 处理关系,您将在数据库中执行更多的“更新”语句。

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      相关资源
      最近更新 更多