Many-to-many relationships

Watch the Many to Many video on YouTube.

Almost every project uses many-to-many relationships, and LINQ to SQL doesn't support them. PLINQO does. Here's a many-to-many relationship between the User and Role tables, through the UserRole table:

Database diagram: the UserRole table links the User and Role tables by UserId and RoleId

Before the code runs, the UserRole table is empty:

The UserRole table with no rows

This code adds a user to a role:

using (var context = new TrackerDataContext())
{
    User u = context.User.GetByKey(1);
    Role r = context.Role.GetByKey(1);
    u.RoleList.Add(r);
    context.SubmitChanges();
}

After the code runs, the UserRole table has the new row:

The UserRole table with one row: UserId 1 and RoleId 1

To control many-to-many associations, see the IncludeManyToMany and AssociationNamingSuffix properties of the Entities template.