Guidelines for Creating WCF RIA Services for LightSwitch
For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.
This topic provides guidelines for creating and consuming Windows Communication Foundation (WCF) Rich Internet Application (RIA) services in a LightSwitch-based application. This topic provides information about the following tasks:
Storing, retrieving, and consuming connection strings in the domain service class of a WCF RIA service
Defining query methods for use in a LightSwitch-based application
Applying attributes to the fields of an entity
For more general information about designing WCF RIA services, see WCF RIA Services.
Storing, Retrieving, and Consuming Connection Strings
To connect to data from within the domain service class of a WCF RIA service, your code must pass a connection string to the data source provider. Developers who consume the service can store the connection string in the web.config file of the LightSwitch application when they connect to the service. In the domain service class of your WCF RIA service, your code can retrieve and consume the connection string.
Storing the Connection String
Developers provide a data source connection string when they connect to your WCF RIA service in LightSwitch. The connection string is saved to the web.config file of the LightSwitch application. For more information, see How to: Connect to Data.
To help developers provide the correct connection string, you can provide helpful text that describes the expected format of the string. This text appears in the Connection String box of the Attach Data Source Wizard. To provide this text, add a DescriptionAttribute attribute to the top of the domain service class.
Retrieving the Connection String
In the domain service class of your WCF RIA service, your code can retrieve the connection string from the web.config file by referring to the fully qualified name of the domain service class (for example, CustomerNamespace.CustomerService
). The following example retrieves a connection string by overriding the Initialize method of the domain service class. If no connection string is found, a hard-coded connection string is used.
Public Overrides Sub Initialize _
(context As System.ServiceModel.DomainServices.Server.DomainServiceContext)
If (WebConfigurationManager.ConnectionStrings.Item(Me.[GetType]().FullName) _
Is Nothing) OrElse [String].IsNullOrWhiteSpace _
(WebConfigurationManager.ConnectionStrings.Item _
(Me.[GetType]().FullName).ConnectionString) Then
_connectionString = "data source=NorthwindDB;initial catalog= " _
& "Northwind;user id=myID;password=myPassword"
Else
_connectionString = WebConfigurationManager.ConnectionStrings.Item _
(Me.[GetType]().FullName).ConnectionString
End If
MyBase.Initialize(context)
End Sub
string _connectionString;
public override void Initialize
(System.ServiceModel.DomainServices.Server.DomainServiceContext context)
{
if ((WebConfigurationManager.ConnectionStrings
[(this.GetType().FullName)] == null) ||
String.IsNullOrWhiteSpace(WebConfigurationManager.ConnectionStrings
[this.GetType().FullName].ConnectionString))
{
_connectionString = "data source=NorthwindDB;initial catalog= " +
"Northwind;user id=myID;password=myPassword";
}
else
{
_connectionString = WebConfigurationManager.ConnectionStrings
[this.GetType().FullName].ConnectionString;
}
base.Initialize(context);
}
Consuming the Connection String
In the domain service class, you can use the connection string to connect to data in any way that you want. However, some technologies in Visual Studio require that you use the connection string in specific ways. For example, if you generate the entities in your service by using an ADO.NET Entity Data Model, your code must return the connection string in the CreateObjectContext method. The following example is based on a scenario in which you have used an ADO.NET Entity Data Model to generate the entities provided by your service. This example overrides the CreateObjectContext method and returns the connection string to the Entity Framework provider.
Protected Overrides Function CreateObjectContext() As NorthwindEntities
Dim Connection As New EntityConnectionStringBuilder()
Connection.ProviderConnectionString = _connectionString
Connection.Provider = "System.Data.SqlClient"
Connection.Metadata = "res://*/NorthwindModel.csdl|" & _
"res://*/NorthwindModel.ssdl|" & _
"res://*/NorthwindModel.msl"
Return New NorthwindEntities(Connection.ToString)
End Function
protected override NorthwindEntities2 CreateObjectContext()
{
EntityConnectionStringBuilder Connection = new EntityConnectionStringBuilder();
Connection.ProviderConnectionString = _connectionString;
Connection.Provider = "System.Data.SqlClient";
Connection.Metadata = "res://*/NorthwindModel.csdl|" +
"res://*/NorthwindModel.ssdl|" +
"res://*/NorthwindModel.msl";
return new NorthwindEntities2(Connection.ToString());
}
Defining Query Methods That Are Consumed in LightSwitch
For each entity in your domain service class, you must identify a default method that LightSwitch can use to return a collection of entities. You can also define other methods that return data.
Identifying a Query Method That LightSwitch Uses by Default
All entities in LightSwitch have at least one method that returns a collection. This method appears in LightSwitch and enables developers to create screens that show lists of information such as customers or orders. You must identify which method you want LightSwitch to use as the default collection method for any given entity in your domain service class. To identify this method, apply the QueryAttribute attribute to the method. Set the IsDefault property of the QueryAttribute to True
. This method must return either an IEnumerable<T> or an IQueryable<T> of the entity type. The collection returned by the method must contain all of the fields of the entity. The query must not accept any parameters. The following example applies the QueryAttribute attribute to the GetCustomers
query method of the Customers
entity.
<Query(IsDefault:=True)> _
Public Function GetCustomers() As IQueryable(Of Customer)
Return Me.ObjectContext.Customers
End Function
[Query(IsDefault=true)]
public IQueryable<Customer> GetCustomers()
{
return this.ObjectContext.Customers;
}
Creating Other Query Methods
You can create as many query methods as you want. Each query method can return one or more entities based on custom logic that you add to the method. In LightSwitch, you can run these methods in your business logic or use them to show data in a screen. Query methods must return an entity type, or an IEnumerable<T> or IQueryable<T> of an entity type. Method parameters must be nullable and simple types that are supported by LightSwitch. For more information about nullable types, see Nullable Value Types or Nullable Types. For more information about simple types that are supported in LightSwitch, see How to: Define Data Fields.
Applying Attributes to Entity Fields
You can apply attributes to the fields of entities in your domain service class. The following table provides guidance on how to use attributes to achieve the effect that you want in LightSwitch.
Attribute | Using this property in LightSwitch |
---|---|
AssociationAttribute | For one-to-many relationships, set the ThisKey property to the primary key of the entity that exists on the one side of the relationship. For zero or one-to-many relationships, set the ThisKey property to the primary key of the entity that exists on the zero or one side of the relationship. For one to zero-or-one relationships, set the ThisKey property to the primary key of the entity that exists on the one side of the relationship. Set the OtherKey property to the primary key of the entity that exists on the zero-to-one side of the relationship. |
DisplayAttribute | In LightSwitch, use the ShortName or Name property to specify the name that you want to appear for this field. Use the Description property to specify the text that you want to appear as a tooltip when users point to a control that contains the field in a screen. |
EditableAttribute | In LightSwitch, if you set the AllowEdit property to False , the ReadOnly property of the field is set to True . |
EnumDataTypeAttribute | If you set the EnumType property to an enumeration, LightSwitch creates a choice list for the field by using the values of the enumeration. |
KeyAttribute | In LightSwitch, use the KeyAttribute attribute if you want the field to be used as the primary key of the entity. You can specify multiple keys. |
RangeAttribute | Use this attribute to set the maximum and minimum values of the field. This attribute has no effect on non-numeric data types. |
RequiredAttribute | In LightSwitch, this property affects only fields that have a string type. If you set the AllowEmptyStrings property of this attribute to False , in LightSwitch, the Is Required property of the field is set to True . |
ScaffoldColumnAttribute | In LightSwitch, if you set the Scaffold property to True , the Display By Default property is set to True. |
StringLengthAttribute | In LightSwitch, use the MaximumLength property to set the Maximum Length property of the field. |
StringLengthAttribute | In LightSwitch, if you apply this attribute, the Display by Default property of the field is set to False . |
The following attributes have no effect in LightSwitch:
ConcurrencyCheck
DataType
DisplayColumn
DisplayFormat
FilterUIHint
MetadataType
RegularExpression
ScaffoldTable
UIHintAttribute