在两个模型之间创建ManyToMany关系

时间:2014-04-17 04:06:59

标签: c# sqlite sqlite-net

我是创建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

1 个答案:

答案 0 :(得分:13)

您可以使用sqlite-net-extensions,它具有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; }
}