How to delete a relationship from many to many table in sqlite-net extension?

邮差的信 提交于 2019-12-25 11:59:19

问题


I've a many to many relationship between students and classes using SQLite-net Extensions:

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
{
    [ForeignKey(typeof(Students))]
    public int StudentFId { get; set; }

    [ForeignKey(typeof(Classes))]
    public int ClassFId { get; set; }
}

I add a relationship this way:

dbConnection.InsertOrReplace(new Students_Classes { StudentFId = sId, ClassFId = cId });

But when I want to delete a relationship:

var validRelation = dbConnection.Find<Students_Classes>(x => x.StudentFId = sId && x.ClassFId = cId);
if (validRelation == null)
    return;

dbConnection.Delete(validRelation);

I get an error says cannot delete because it has no PK. I can get a Student with all his classes, remove one class then save it again with his classes but there can be performance issues.

How to remove a relationship in a many to many relationship? thanks.


回答1:


Pretty easy, just add a primary key to your relationship class:

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

    [ForeignKey(typeof(Students))]
    public int StudentFId { get; set; }

    [ForeignKey(typeof(Classes))]
    public int ClassFId { get; set; }
}

Anyway using SQLite-Net Extensions you don't need to manage the relationship table by yourself, just add or remove the children item from the list and call UpdateWithChildren on the object.

Take a look at the Integration Tests project to see how it works.



来源:https://stackoverflow.com/questions/26412411/how-to-delete-a-relationship-from-many-to-many-table-in-sqlite-net-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!