简体   繁体   中英

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

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

You do not have a primary key in your Students_Classes class. That is the problem.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM