如何在sqlite-net扩展中删除多对多表的关系?

时间:2014-10-16 19:31:12

标签: c# sql sqlite sqlite-net sqlite-net-extensions

我使用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; }
}

我以这种方式添加关系:

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

但是当我想删除一段关系时:

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

dbConnection.Delete(validRelation);

我收到错误cannot delete because it has no PK。我可以让他的所有课程的学生,删除一个课程然后再与他的课程保存,但可能会有性能问题。

如何删除多对多关系中的关系?感谢。

1 个答案:

答案 0 :(得分:1)

非常简单,只需在关系类中添加一个主键:

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

无论如何使用SQLite-Net Extensions,您不需要自己管理关系表,只需在列表中添加或删除子项,然后在对象上调用UpdateWithChildren

查看“集成测试”项目,看看它是如何工作的。