How to Create a Many-to-Many Relationship (Andy Kung)

How to Create a Many-to-Many Relationship (Andy Kung)

Rate This
  • Comments 36

Note: This article has been updated for Beta 2 on 3/17/2011

Many business applications require many-to-many relationships. For example, an author can write many books, and a book can be written by many authors. To model this relationship in LightSwitch, you need to create a mapping table for the 2 objects (e.g. AuthorToBook mapping table for Author and Book).

In this post, we will create a movie database application. This application requires a many-to-many relationship for the movie and genre entities. Meaning, each movie can have many genres, and each genre can have many movies. In addition, we will build a “list-box mover” UI to interact with the relationship. To give you an idea of what we’re building, here is a sneak peek of the screen you will end up with by the end of the post.

image

Start with data

We will start by adding a Movie table and a Genre table, each with some relevant fields.

Movie

  • Title (String, required)
  • ReleaseDate (Date, required)
  • Length (Integer, required)
  • Storyline (String, required)

image

Genre

  • Name (String, required)

image

Next, we need to create a mapping table between Movie and Genre. Let’s create a new table called MovieGenre, but don’t specify any additional fields.

image

Then, click “+ Relationship” button in the command bar to open the “Add New Relationship” dialog. We will now set up the many-to-many relationship.

image

Since it is a mapping table, each entry only contains a reference to a movie and a genre. Using the dialog, we want to make sure “one Movie can have many MovieGenre,” and “one Genre can have many MovieGenre.

image

image

We should now have the 3 tables set up as follow.

image

We can also add a summary field to the mapping table so it has a meaningful string representation by default.

Private Sub Summary_Compute(ByRef result As String)

    result = Genre.Name

End Sub

For more details of how to customize an entity’s summary field, please see Getting the Most out of LightSwitch Summary Properties by Beth Massi.

Create a Screen

Now that we have the data set up, let’s create a screen via the “Add New Screen dialog.” We will use “New Data Screen” template and make sure Movie is selected under “Screen Data” and both Movie Details and Movie MovieGenres are checked. This ensures the screen will include data about the movie as well as its related genres. Click OK.

image

Screen designer now appears. You should have a screen like this:
image

If we run the application (F5) at this point, you will see a screen that lets you enter basic movie information as well as a grid for its genres.

image

“List-Box Mover” UI

Let’s customize the screen to make it more user-friendly by creating a, for lack of a better term, “list-box mover” UI. It has essentially 2 lists. One shows the genres associated with the movie, and the other shows all the possible genres a user can choose from. User can then use an “Add <<” and “Remove >>” button to move things around.

Our screen already has the list of genres associated with the movie (currently showing as a grid). We still need a list of all possible genres. To do this, we will add a screen query that returns all genres. Go back to the screen designer. Click “Add Data Item” button in the command bar.

image

Select Query, Genres, and click OK.

image

You should now see the newly created Genres in the members list of the screen designer.
image

For the “list-box mover” UI, we essentially want 3 columns: movie genre list, button group, and all-genre list. I find it useful to draw out what I want to build in blocks first. In this case:

clip_image017

We will use Columns Layout instead of Rows Layout for the children group. Use the “+ Add” button to add Genres below Movie Genres. Change both collections to use List control instead of Data Grid control. Remove all the commands associated with both Lists.

image

Now we have 2 columns for genres. We need a middle column for the buttons. Create a group in the middle using Rows Layout called Button Group.

image

Set the horizontal and vertical alignment of the Button Group to Left and Center in the Properties.

image

Since we want to have 2 buttons stacked vertically in the middle column, create 2 groups within the Button Group using Rows Layout.

image

Right click on Group 1 to add a button. Rename the generated method to AddGenre. Similarly, add a button to Group 2 with a RemoveGenre method. We can change the display name of the buttons to be “<<” and “>>”.

image

Finally, we can write some code for AddGenre and RemoveGenre. Double click on the buttons to edit screen code:

        Private Sub AddGenre_Execute()

            If (Genres.SelectedItem IsNot Nothing) Then

                Dim mg As MovieGenre = MovieGenres.AddNew()

                mg.Movie = Me.MovieProperty

                mg.Genre = Genres.SelectedItem

            End If

        End Sub

 

        Private Sub RemoveGenre_Execute()

            MovieGenres.DeleteSelected()

        End Sub

That’s it! Now run the application and play with the “list-box mover” UI. In this example, I pre-populated the genre list using another screen.

image

Hope that helps!

-andy

Leave a Comment
  • Please add 7 and 2 and type the answer here:
  • Post
  • Actually best after:

                      MovieGenre mg = this.MovieGenres.AddNew();

                      mg.Movie = this.MovieProperty;

                      mg.Genre = this.Genres.SelectedItem

                      mgExists.Delete(); // Add this line to delete instance after test

  • it's really helpful for me, thanks ~

    and lightswitch is so powerful that i can't help getting to learn it.

  • Can this be done on a List and Details screen. I am have issue getting it to work.  works fine on a New Data Screen

  • I thought this was exactly what I was looking for until I realized this is for WinApp and not for HTML client. I am hampered from doing further development with LightSwitch since this feature is necessity because of the DB I inherited uses a lot of many to many relationships that uses an intermediary table to connect the two outside tables.

    I tried doing this in code by passing in an ID to showScreen() method in code but having issues doing that.

    * Is there a time table for having this many to many relationships in the HTML client version?

    * Is there a way of doing this in code?

    * If I use a DB View to create a screen and then pass the ID from across how can I achieve this in code?

    I love where the LightSwitch team is going with this and I am hoping the HTML Client receives more traction. This is a great tool and I want to introduce it into my company.

  • @VBMan_OC - Here's an article from Heinrich on ways you can do this in the HTML client: blogs.msdn.com/.../many-to-how-many-html-edition-heinrich-wendel.aspx

    Cheers,

    -Beth

  • Although quite old, I found this post useful for my VS 2013 project.

    I had a problem though with the removal of duplicates code provided inline to this post.

    I have created a VB project an implemented the same concepts. When I:

    1. Attempt to Add a record from List A that already resides in List B, it does indeed not add it;

    2. Add a record from List A that doesn't exist in List B, it adds it (to List A).

    When I attempt to save the form data, I'm presented with the same issue @Pedz commented a while back. I receive form validation errors that my objects is either not set or no longer exists.

    Can anybody help me?

Page 3 of 3 (36 items) 123