Benefits of Using [ManyToMany]
with a Junction Table
Flexibility: Both classrooms and students can be associated with multiple records. This allows for real-world scenarios where a student can attend multiple classes, and a class can have multiple students.
Efficient Data Management: Instead of duplicating data (e.g., storing a list of students inside each classroom record or vice versa), you store the relationships separately in the ClassroomStudent
table.
Automated Relationship Handling: The [ManyToMany]
attribute simplifies CRUD operations on related entities. The ORM manages inserting, updating, and deleting relationships in the junction table behind the scenes.
ClassRoomItem Table: Represents the classrooms in the system. Each classroom can have multiple students associated with it, which is managed through the Students
list using a many-to-many relationship.
Student Table: Represents the students in the system. Each student can be enrolled in multiple classrooms, which is managed through the ClassRooms
list using a many-to-many relationship.
ClassroomStudent Junction Table: Manages the many-to-many relationship by linking ClassRoomItem
and Student
together. This table contains two foreign keys:
ClassroomId
references theClassRoomItem
table.StudentId
references theStudent
table.
Let’s create Dotnet maui project
Add this three plugin :
We will be adding this 3 packages inside our project:
<PackageReference Include=”sqlite-net-pcl” Version=”1.9.172″ />
<PackageReference Include=”SQLiteNetExtensions.Async” Version=”2.1.0″ />
<PackageReference Include=”SQLitePCLRaw.bundle_green” Version=”2.1.2″ />
MainPage.xaml
MainPage.xaml.cs
App.xaml.cs
ClassRoomViewModel.cs
ClassRoomDatabase.cs
ClassRoomItem.cs
ClassroomStudent.cs
Student.cs