Silverlight and RIA: Enum Properties
Posted
Tue, Nov 10 2009 12:58
by
Deborah Kurata
I mentioned in this prior post that RIA Services did not know how to handle properties that have an Enum data type. The problem is not really that RIA Services does not know how to handle the properties; rather it does not have any knowledge of the Enum itself.
Take this example.
In C#:
public enum CustomerTypeOption
{
Consumer,
Corporation,
Education,
Government
}
private CustomerTypeOption _CustomerType;
public CustomerTypeOption CustomerType {
get { return _CustomerType; }
set { _CustomerType = value; }
}
In VB:
Public Enum CustomerTypeOption
Consumer
Corporation
Education
Government
End Enum
Private _CustomerType As CustomerTypeOption
Public Property CustomerType() As CustomerTypeOption
Get
Return _CustomerType
End Get
Set(ByVal value As CustomerTypeOption)
_CustomerType = value
End Set
End Property
This code resides in a Customer class like the one shown in this prior post. If you create a CustomerService domain services class, Silverlight will generate a proxy class containing all of the Customer class properties. However, the generated code contains a syntax error because it does not understand the CustomerTypeOption type.
This problem can be solved by sharing the Enum with Silverlight following the technique detailed in this prior post and shown below.
Let's go through the steps in detail:
1. Add a new file to your business object component and call it Customer.shared.vb (if your component is VB.NET) or Customer.shared.cs (if you are using C#).
2. Add the partial keyword to the class name in the file as shown in the code below.
3. Cut the Enum definition from the Customer class and paste it into this partial class.
In C#:
public partial class Customer
{
public enum CustomerTypeOption
{
Consumer,
Corporation,
Education,
Government
}
}
In VB:
Partial Public Class Customer
Public Enum CustomerTypeOption
Consumer
Corporation
Education
Government
End Enum
End Class
4. Right click on the Web project linked to your Silverlight project and select Add | Existing Item.
5. In the Add Existing Item dialog, select the file and select Add As Link from the Add button drop down menu.
This links the file between your business object class library project and the Web project linked to your Silverlight project.
6. Build the solution.
Silverlight should now have a copy of the Customer.shared.vb or Customer.shared.cs file under the Generated_Code node. Since the Enum is now defined in the Silverlight project, your CustomerType property in the generated code should compile without errors.
Use this technique any time you want to share an Enum between your business object class library project and your Silverlight project.
Enjoy!