While using Visual Studio LightSwitch with an external database, I came across a minor issue when creating a new entity.
I’m using the AdventureWorks Light database in my exploration. Most of the tables contain a field called rowguid.
The problem I encountered is how to initialize a property of type Guid when adding a new record.
For example, when you create a Customer entity using the SalesLT.Customer table in the AdventureWorks Light database, the Customer entity appears in the designer as follows:
I added a SearchCustomer screen and added an Add… button in the Command Bar.
When I run the app and click Add… button in the Customer screen, LightSwitch creates an empty GUID in the rowguid field:
The behavior I want is to automatically create a new Guid.
As a side bar conversation, you can argue the need to display this field. I believe in most cases you would want this field hidden. Only in a few cases, such as some type of management screen, would you want the Guid which identifies this row uniquely to be shown.
In any case, I don’t want to require the user to enter data in this field or for the field to be initialized to 0 for each new record.
Auto generating the Guid is accomplished by adding code in the entity’s Created method.
The first step is to have LightSwitch generate code that’s called when it creates a new Customer entity. Open the Customer Entity in the designer. Click Write Code in the main menu, then click Customer_Created in the drop down menu.
Next, add code to initialize the Customer’s rowguid property.
Now when you add a new customer record, the rowguid is initialized: