A prettier way to use Enums
I think we have all struggled with using Enums with Linq, most especially when trying to plug them into your results. A far better approach is to decorate your classes with them. Let me explain
We start by declaring a typical Enum class - something like this.
public enum OrderStatus
{
/// <summary>
/// Pending
/// </summary>
Pending = 10,
/// <summary>
/// Processing
/// </summary>
Processing = 20,
/// <summary>
/// Complete
/// </summary>
Complete = 30,
/// <summary>
/// Cancelled
/// </summary>
Cancelled = 40
}
Then when we want to take advantage of it - in our Orders class we declare a string of OrderStatus - keep in mind our database only has OrderStatusId. Here is what this property looks like.
public OrderStatus OrderStatus
{
get
{
return (OrderStatus)this.OrderStatusId;
}
set
{
this.OrderStatusId = (int)value;
}
}
In our query we only return the OrderStatusId but then on the page we use "OrderStatus" and the value returned is the string from our Enum.
Voila - no struggling within the Linq.
We start by declaring a typical Enum class - something like this.
public enum OrderStatus
{
/// <summary>
/// Pending
/// </summary>
Pending = 10,
/// <summary>
/// Processing
/// </summary>
Processing = 20,
/// <summary>
/// Complete
/// </summary>
Complete = 30,
/// <summary>
/// Cancelled
/// </summary>
Cancelled = 40
}
Then when we want to take advantage of it - in our Orders class we declare a string of OrderStatus - keep in mind our database only has OrderStatusId. Here is what this property looks like.
public OrderStatus OrderStatus
{
get
{
return (OrderStatus)this.OrderStatusId;
}
set
{
this.OrderStatusId = (int)value;
}
}
In our query we only return the OrderStatusId but then on the page we use "OrderStatus" and the value returned is the string from our Enum.
Voila - no struggling within the Linq.
Comments