Entity Framework 6 Enums with String column
I recently watched Jimmy Bogard's excellent NDC presentation on Domain models to learn about how to implement a real world domain model.
One of the things Jimmy does in his presentation is to refactor his enum to use a base class allowing far more expressive enums with custom behaviour
There are a few versions of this custom enum base class around but I'm going to be using this one.
Annoyingly Entity Framework (EF) doesn't support mapping database fields to enums unless you use an int column in your database. This might be good enough for your implementation however it seems a bit fragile to couple your database to a mystery int defined in code somewhere which could be changed by any user who doesn't realise what they're changing.
For a marginally less fragile and more domain model friendly enum I used an adapted version of Jimmy's enumeration class:
The main change is to the DisplayName property. We add a setter because Entity Framework is only going to bring back the string display name and we need to map to the underlying value field to get the proper enum.
public string DisplayName
{
get
{
return this.displayName;
}
// Entity Framework will only retrieve and set the display name.
// Use this setter to find the corresponding value as defined in the static fields.
protected set
{
this.displayName = value;
// Get the static fields on the inheriting type.
foreach (var field in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
{
// If the static field is an Enumeration type.
var enumeration = field.GetValue(this) as Enumeration;
if (enumeration == null)
{
continue;
}
// Set the value of this instance to the value of the corresponding static type.
if (string.Compare(enumeration.DisplayName, value, true) == 0)
{
this.value = enumeration.Value;
break;
}
}
}
}
This simply checks the static fields on the instance of the enumeration class and finds the enumeration with the matching name.
We also change the private displayName and value fields to remove the readonly access modifier (and the underscores because I've never been able to adapt to the convention):