在两个模型之间创建ManyToMany关系
本文关键字:之间 创建 ManyToMany 关系 模型 两个 | 更新日期: 2023-09-27 17:58:39
我是创建Windows应用商店应用程序的新手,它需要使用数据库。我已经选择了sqlite,并且正在使用sqlite-net包。然而,我不确定如何在两个模型之间创建m2m关系。
class ModelA
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string name { get; set; }
<relationship to ModelB>
}
class ModelB
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string name { get; set; }
}
我需要使用列表吗?还是字节[]?我如何保证该属性将被限制为ModelB
?
您可能可以使用sqlite网络扩展,它有一个ManyToMany
属性,似乎非常适合您的需求。这是他们网站上使用它的一个例子。
public class Student
{
[PrimaryKey, AutoIncrement]
public int StudentId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[ManyToMany(typeof(StudentsGroups))]
public List<Group> Groups { get; set; }
public int TutorId { get; set; }
[ManyToOne("TutorId")] // Foreign key may be specified in the relationship
public Teacher Tutor { get; set; }
}
public class Group
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string GroupName { get; set; }
[ForeignKey(typeof(Teacher))]
public int TeacherId { get; set; }
[ManyToOne]
public Teacher Teacher { get; set; }
[ManyToMany(typeof(StudentsGroups))]
public List<Student> Students { get; set; }
}
public class StudentGroups
{
[ForeignKey(typeof(Student))]
public int StudentId { get; set; }
[ForeignKey(typeof(Group))]
public int GroupId { get; set; }
}