Friday, August 20, 2010

LightSwitch Table Relationships


In my last post I introduced Microsoft's new RAD tool called Visual Studio LightSwitch. In the example in that post I showed how to create an application with a single table, now I’ll explain how to do table relationships.

Last time I created an employee table. Now I want a table that lists the work history for each employee. First add a new table called WorkHistory. You will notice that I did not put a foreign key on the WorkHistory table to relate it to the Employee table; LightSwitch will take care of this for you.

clip_image002

A note on table naming. LightSwitch tries to be very helpful in naming your tables. The name you type at the top of the table editor is actually the entity name, it represents a single thing. The name that shows up in the Solution Explorer is the table name which LightSwitch will try to pluralize for you. So the WorkHistory entity creates a table called WorkHistories. For this reason do not pluralize the entity name. If you were to enter WorkHistories as the entity name you would end up with a table called WorkHistoriesSet.

Once you have created the table you need to setup the relationship by clicking the Relationship… button which brings up the relationship designer:

clip_image004

The options are set at the top of the screen and relationship will be displayed both graphically and in plain English. The Navigation Property is the name of the property that will be created on each table to manage the relationship.

The change will not automatically show up in the Add New screen I created last time, so the easy fix is to delete that screen and add a new one. When you select Employee for the Screen Data you will now get the option of including the Employee WorkHistories on the screen.

clip_image006

When you run the application you will now have an Add New screen where the employee's details and work history can be edited.

clip_image008

No comments: