I'm using Entity Framework Code First CTP 5 for a current project. There is still no enum support in Entity Framework so this is what I am using in order to avoid having magic numbers or casts littered throughout my code.
Simplified Example:
Domain Model Consumed by Code First
public class Address
{
// This would normally be an enum
public int Type { get; set; }
}
Repository
public class AddressRepository
{
public Add(Address address)
{
// Compare using enum semantics
if (address.Type == AddressType.Home)
// Do something
context.Add(address);
}
}
View Model
public class AddressVM
{
// Using the AddressType class for the view model
public AddressType Type { get; set; }
public AddressVM(Address address)
{
this.Type = address.Type;
}
}
Enum Replacement Class
public interface IEnumClass
{
List<string> Properties { get; }
}
public class AddressType : IEnumClass
{
public static int Home { get { return 0; } }
public static int Work { get { return 1; } }
public List<string> Properties { get { return properties; } }
private List<string> properties;
private int id;
public AddressType()
{
SetProperties();
}
public AddressType(int id)
{
this.id = id;
SetProperties();
}
private void SetProperties()
{
properties = this.GetType().GetProperties(BindingFlags.Public|BindingFlags.Static)
.Select(x => x.Name).ToList();
}
public static implicit operator AddressType(int id)
{
return new AddressType(id);
}
public static implicit operator String(AddressType addressType)
{
return addressType.properties[addressType.id];
}
public static implicit operator int(AddressType addressType)
{
return addressType.id;
}
}
My Personal Assessment
Pros:
- Allows me to write business rules without using magic numbers
- Uses the same semantics/syntax as enums for easy refactoring down the road
- Allows for an implicit conversion to a string for the view model
- My select list factory class can easily be made to accept any
IEnumClass
and generate a select list for the view model
Cons:
- A little verbose
- As far as I can tell it is impossible to use a nice abstract generic class because all the actual work uses implicit type casting
I'm asking for feedback here because I'm a total novice programmer so I want to solicit some critiques before implementing something I just came up with!