Entity Framework Enum and string association

c# entity-framework entity-framework-6

Question

I want to use the method in this article to implement friendlier ToString() outputs for my enum types. I would like to know how this can be done in Entity Framework's auto generated Enum codes? Would I have to modify the code generation template (if so, can someone kindly give me some guidance since the template is rather complicated), or can someone suggest an alternative method?

Thanks!

Accepted Answer

You can use your own enum type in your EF model, instead of creating a new enum in the model designer. Here's how:

In the model designer, rght click on surface and select:

Add New -> Enum Type...

In the dialog, just set checkbox:

Reference external type

and enter your type: namespace.MyEnum

Then create columns in your tables to use this type.

Since you're likely going to modify the existing model, make sure there is no confusion between enum type from the model and (external) enum type from your code. Best approach would be to remove the enum type you previously had created in the model and adjust the columns to use the associated enum type from your code.

Now, you can declare your enum type with description attributes as you planned.


Popular Answer

You don't need to make workarounds for enums. They're supported in the latest Entity Framework.

To make your enums friendly to your website you can use attributes. Here is sample attribute:

public class EnumDescription : Attribute
{
    public string Text { get; private set; }

    public EnumDescription(string text)
    {
        this.Text = text;
    }
}

Mark your enums with attribute:

public enum DaylightSavingTime
{
    [EnumDescription("Detect automatically")]
    Auto = 0,
    [EnumDescription("DST always on")]
    AlwaysOn = 1,
    [EnumDescription("DST always off")]
    AlwaysOff = 2
}

Add extensions to enable ToDescription() method:

public static class EnumExtensions
{
    public static string ToDescription(this Enum enumeration)
    {
        Type type = enumeration.GetType();
        MemberInfo[] memInfo = type.GetMember(enumeration.ToString());

        if (null != memInfo && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumDescription), false);
            if (null != attrs && attrs.Length > 0)
                return ((EnumDescription)attrs[0]).Text;
        }

        return enumeration.ToString();
    }
}

Usage:

var blabla = DaylightSavingTime.Auto;
Console.WriteLine(blabla.ToDescription());

Output:

Detect automatically




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why