问题描述
我使用 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);
我收到一条错误消息,说无法删除,因为它没有 PK
.我可以让一个学生拥有他的所有课程,删除一个课程,然后再将其与他的课程一起保存,但可能会出现性能问题.
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.
推荐答案
很简单,只需在关系类中添加一个主键即可:
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; }
}
无论如何使用 SQLite-Net 扩展,您都不需要自己管理关系表,只需从列表中添加或删除子项并在对象上调用 UpdateWithChildren
.
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.
这篇关于如何删除sqlite-net扩展中多对多表的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!