left-icon

LightSwitch Succinctly®
by Jan Van der Haegen

Previous
Chapter

of
A
A
A

CHAPTER 3

The Entity Designer

The Entity Designer


Creating a Task entity with simple and computed properties

In the Solution Explorer, right-click on Application Data and select Add New Table.

Our second entity will be called Task, and it will have a couple of properties.

Task entity in the Entity Designer

Figure 8: Task entity in the Entity Designer

For each of the properties, the Entity Designer shows three columns: the name of the property, the type, and a check box that indicates if a value is required.

When you select a particular property, additional extended properties can be edited in the Properties window where you can take more fine-grained control over how the entity or its properties are visualized, stored, validated, etc.

For example, I removed the maximum length of the Description property as shown in the following figure.

Clearing the maximum length

Figure 9: Clearing the maximum length

Specifying the Maximum Length for Description field here is a great example of the “Don’t Repeat Yourself” (DRY) principle that I implicitly referred to in the preface. In the entire application, there is only one source of truth that controls how long the Description property can be. This information will be used to create the actual database fields correctly, but also to implement validation on the server and the client.

Length validation is still active for the Name property

Figure 10: Length validation is still active for the Name property

Similarly, I limited the values of the PercentageComplete property to fall between 0 and 100 (inclusive).

Limiting the range of the PercentageComplete property

Figure 11: Limiting the range of the PercentageComplete property

Besides validation, these extended properties can also be used to control how this property will be visualized in the client by default. The Priority property is stored as an integer, but visualized to the user in a more textual way by clicking on the Choice List… option in the Properties window.

Click the Choice List… link in the extended properties panel

Figure 12: Click the Choice List… link in the extended properties panel

This opens a pop-up where you can define the available choices and their display names.

Limiting the allowed choices for the Priority property

Figure 13: Limiting the allowed choices for the Priority property

You might notice that some properties have an icon next to their name. The icon that looks like a key is straightforward: it indicates a field that will be used as a primary key column in the database. The icon that looks like a calculator however, warrants some extra explanation.

LightSwitch supports computed properties. These are properties that are not stored in the database but instead calculated at run time on the tier (client or server) where they are accessed. Turning a simple property into a computed property is done by selecting it, and then selecting the Is Computed check box in the Properties window.

Making the State and Summary properties computed properties

Figure 14: Making the State and Summary properties computed properties

Click on the Edit Method link to access a code editor where you can implement the business logic for how to calculate this property. In the following code sample, I fill the blank State_Compute method that LightSwitch created for me with the desired business logic.

namespace LightSwitchApplication

{

    public partial class Task

    {

        partial void State_Compute(ref string result)

        {

            if(this.PercentageComplete == 100){

                result = "Complete";

            }

            else

                if (this.DueDate > DateTime.Today) {

                    if (this.PercentageComplete == 0){

                        result = "Pending...";

                    }

                    else {

                        result = "Started";

                    }

                }

                else {

                    result = "Overdue!";

                }

        }

        partial void Summary_Compute(ref string result)

        {

            result = this.Name + "(" + this.State + ")";

        }

    }

}

The State property is a simple label based on the PercentageComplete and DueDate properties. For tasks, I decided to compute a Summary property as well to help represent the entity as a string. By default, if an entity needs to be represented as a single line, LightSwitch shows the value of the first string property. Overriding this convention can be done by selecting the entity itself and choosing the desired entity property for the Summary Property option in the Properties window.

For each entity, you can select the Summary property

Figure 15: For each entity, you can select the Summary property

At first glance, the Entity Designer looks like a database designer, but you should really try to think of it as a domain object designer, since the choices made here will have effects throughout the application, not just in the database tier. This becomes even more apparent in our third entity: Person.

Creating a Person entity with clever reuse of existing business types

Entity Designer for a Person Entity

Figure 16: Entity Designer for a Person Entity

In this entity, we’ll stray away from the simple property types used before (Boolean, Date, DateTime, Decimal, Double, Guid, Integer, Long Integer, Short Integer, and String) and encounter some properties of types that you would not normally find in the normal database lingo (e.g., Phone, Email, and Avatar). In the LightSwitch Entity Designer, one property type is a business type. Besides the simple property types already listed, LightSwitch understands percentages, email addresses, phone numbers, the concept of money, what an image is, and how web addresses work. Business types come with specific validation rules, and often tailored controls are used by default to visualize this property.

LightSwitch already understands some special business types

Figure 17: LightSwitch already understands some special business types

If there’s a business type that your business needs but is not included in Visual Studio LightSwitch, you can easily create custom business types using the Extensibility Toolkit.

Taking full control

Also, remember that by using the Write Code button, you can take control of any part of the application. This extension point allows you to quickly add logic that controls how particular properties are computed as shown before, allows you to implement your business rules, custom validation, screen-level or application-level visualizations, and much more. I will later refer back to this as level-one extensibility.

One example of this extensibility we can add to our application is to add a fresh task each time a Project is created. The code for this is added by clicking on the Write Code button in the Entity Designer for the Project entity, and simply adding the following code:

namespace LightSwitchApplication

{

    public partial class Project

    {

            partial void Project_Created()

            {

                var firstTask = this.Tasks.AddNew();

                firstTask.Description = "A first task for every project!";

                //Fill in other required properties here.

            }

    }

}

This code will execute when end users create a new Project, no matter if they are using the client from the UI, the code behind, or even if they are connecting to the server directly with another client. We’ll discuss that last scenario later.

Don’t forget to design the relationships

Before finishing this brief introduction to the Entity Designer and exploring the application we’ve just built, we’ll need to define the relationships between Projects, Tasks, and People. This is done by clicking on the Add Relationship… button in the Entity Designer toolbar.

Using the Entity Designer toolbar to define relationships

Figure 18: Using the Entity Designer toolbar to define relationships

In the Add New Relationships dialog that opens, you can define a new relationship between the selected entity and any other entity.  We are now using the Entity Designer to model our own entities, for which tables will be generated. However, as will be described in a bit, you can also model LightSwitch entities over databases or other data sources that already exist. These might be legacy databases that do not have correct relationships defined and are not under your control to modify. By using the LightSwitch relationship designer, you can still design the relationships between these entities, or even between related entities from different data sources!

Create a new relationship between Person and Task such that one person can have many tasks, but a task can only be assigned to a single person. The following figure shows how this relationship can be defined.

Defining a relationship between Task and Person

Figure 19: Defining a relationship between Task and Person

Similarly, let us create a new relationship between Task and Project. Because some tasks are grouped together and others are just small to-dos, the relationship between Task and Project is defined as a “zero-or-one to many” relationship.

Defining a relationship between Task and Project

Figure 20: Defining a relationship between Task and Project

While defining relationships, you will notice that some relationship types like “zero-or-one to zero-or-one”, “one to one” and “many to many” are not directly supported in LightSwitch, but they can often be accomplished through the use of a link table and by making use of level-one extensibility.

To play around with the application we have designed so far (I intentionally use the term “designed” and not “coded”), add two List and Details screens called AllPeople and AllTasks for the respective entities by following the instructions on creating screens in Chapter 2.

Application with three entities and corresponding screens

Figure 21: Application with three entities and corresponding screens

Congratulations, you now have a fully working application to help you take back control of your time! As you can see in the following figure, I have added two tasks to my application: Create some entities and Do the dishes. Feel free to create your own test data and tasks.

Our first application

Figure 22: Our first application

Before moving on, I want to emphasize that the Entity Designer should be considered a business entity (domain model) designer, not a database designer.

The business entities designed in the Entity Designer, their properties, the business types of their properties, and the extended properties thereof, including the validation, are used by LightSwitch throughout the application in the data tier, on the server, and on the client.

Data-in

It’s a common scenario that the data from one application has to be accessible in another application. LightSwitch applications are far from isolated data silos, and the IDE has out-of-the-box support for both data-in and data-out scenarios.

To explore the former, remember that we conveniently clicked on the Create New Table link on the LightSwitch home screen and started designing our first entity.

These entities will be stored in an intrinsic data source called ApplicationData by default.

There can be many data sources in a LightSwitch project

Figure 23: There can be many data sources in a LightSwitch project

If you want to use LightSwitch to work with existing data, use the second link on the LightSwitch home screen—Attach to an external Data Source. This will start a wizard to help you connect to one of the following sources:

  • An existing database.
  • A SharePoint site.
  • An OData endpoint.
  • A WCF RIA service.

The Data Source wizard helps you connect to external data sources

Figure 24: The Data Source wizard helps you connect to external data sources

The Attach Data Source Wizard will add a non-intrinsic data source to your application and allow you to design your business entities over the data with some validation limitations (options like “is the property required”, “maximum length”, and the compatible Business Type of the properties are limited depending on the source data type).

To OData or not to OData

The option to connect to an OData service in LightSwitch 1.0 has been kept for Visual Studio LightSwitch 2012.

 Open Data Protocol

Figure 25: Open Data Protocol

OData, short for Open Data Protocol, is an industry standard that has been emerging fast over the last couple of years and is now widely adopted as a standard way to exchange data over the web. More technically, it’s a protocol defined by Microsoft that defines a REST implementation. On the OData webpage you can find an ever-growing list of OData producers, including SSRS (SQL Server Reporting Services), Microsoft Dynamics CRM 2011, Windows Azure table storage, and the famous Northwind database.

If you want to test this data-in scenario, select the OData Service option in the Attach Data Source Wizard and then click Next.

In the Connection Information, use the following OData endpoint as your OData Source Address: http://services.odata.org/Northwind/Northwind.svc/. This endpoint requires no authentication, so select None as the selected Login Information, and then click Next.

Connecting to an external OData service

Figure 26: Connecting to an external OData service

Once a successful connection has been made, LightSwitch investigates the metadata of your data source and allows you to import one or more data entities as business entities.

Defining which entities to import

Figure 27: Defining which entities to import

Select the Suppliers check box; Products will also be imported automatically because of the relationship between the two, and then click Next to finish the wizard.

Notice that although the data type of the Supplier entity’s Phone property is String, you can use the Entity Designer to remap it to the Phone Number business type.

Remapping data types to business types

Figure 28: Remapping data types to business types

Data-out

Another out-of-the-box feature is the supported data-out scenario. For each of your data sources, intrinsic or not, LightSwitch will generate and host an OData endpoint that exposes your business entities.

The endpoint can be found at http://<UrlToTheApplication>/<DataSourceName>.svc.

Browsing to the OData endpoint

Figure 29: Browsing to the OData endpoint

If the generated Silverlight application doesn’t fit your business needs, you can reach these OData endpoints in numerous other client technologies, including (but not limited to):

One important thing to note about these OData endpoints is that they do not simply expose your data, but expose your business entities with respect to their business logic, security settings, and default or coded validation rules.

Blending data-in and data-out

One powerful way to use LightSwitch is to use it in combination with other technologies, combining both data-in and data-out scenarios. Because of the choice to use OData in the LightSwitch middle-tier, LightSwitch can be used not only to create simple CRUD applications, but to accomplish complex data ecosystems.

LightSwitch mash-ups between data-in and data-out scenarios

Figure 30: LightSwitch mash-ups between data-in and data-out scenarios

Another powerful way to use LightSwitch is to use it solely for its data-in and data-out functionality. This makes it easy to convert an older WCF RIA service or SQL database to an OData service, or offer a limited view on your internal SharePoint site to an external party.

Both the image above and the links were gathered by Beth Massi (see Chapter 7).


Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.