I'm new to creating a Windows Store app and it requires a use of a database. I've settled for sqlite and am using the sqlite-net package. However, I'm unsure of how to create a m2m relationship between two models.
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; }
}
Would I have to use a List? or a byte[]? How can I guarantee the property will be constrained to ModelB
?
To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.publications.add(p1) Traceback (most recent call last): ...
By default, Django model relationships are established on the primary key of a model which in itself defaults to a model's id field. For example, the field menu = models. ForeignKey(Menu) stores the id from a Menu instance as the relationship reference.
A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.
The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set. Syntax: field_name = models.Field(related_name="name")
You might be able to use sqlite-net-extensions, it has a ManyToMany
attribute that seems perfect for your needs. This is an example of its use from their website.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With