This page is a work in progress and may undergo further revisions, updates, or amendments. The information contained herein is subject to change without notice.
Related collections support the editing of many-to-many relationships in UI Builder. These are used when multiple entities from one collection are linked to multiple entities from another collection, commonly represented through a junction table.
Example Use Case
A classic example is the relationship between Students and Courses, where each student takes many courses, and each course has many students.
Collections Representation
This is how the collections would be represented:
The models representing the entities would be as follows:
[TableName("Students")]
[PrimaryKey("Id")]
public class Student
{
[PrimaryKeyColumn]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
[TableName("Courses")]
[PrimaryKey("Id")]
public class Course
{
[PrimaryKeyColumn]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
[TableName("StudentsCourses")]
[PrimaryKey(new[] { "StudentId", "CourseId" })]
public class StudentCourse
{
[PrimaryKeyColumn]
public int StudentId { get; set; }
[PrimaryKeyColumn]
public int CourseId { get; set; }
}
Defining a Related Collection
To define a related collection, follow these two steps:
Add the collection definition
Add the related collection entity picker and definition
Collection definition
Define a related collection by calling the AddRelatedCollection method on the collection config builder instance.
Using the AddRelatedCollection() Method
This method adds a related collection to the current collection, specifying names, descriptions, and default icons. The ID property must be defined, and the relation configuration defines the junction entity with references to parent and child entities.
{
var db = _scopeProvider.CreateScope().Database;
var type = entity.GetType();
var studentId = type.GetProperty("StudentId").GetValue(entity);
var courseId = type.GetProperty("CourseId").GetValue(entity);
// delete relation if exists
db.Execute("DELETE FROM StudentsCourses WHERE StudentId = @0 AND CourseId = @1",
studentId,
courseId);
db.Execute("INSERT INTO StudentsCourses (StudentId, CourseId) VALUES (@0, @1)",
studentId,
courseId);
return entity;
}