Entity Framework Enum and string association

c# entity-framework entity-framework-6


I want to build friendlier ToString() outputs for my enum types using the approach in this piece. How can this be accomplished using Entity Framework's automatically created Enum codes, please? Would I need to change the code generation template (and if so, could someone please offer me some assistance as the template is quite complicated), or can someone recommend another approach?


1/13/2014 5:55:30 AM

Accepted Answer

Instead of generating a new enum in the model designer, you can use your existing enum type in your EF model. This is how:

Right-click on surface in the model designer and choose:

Enum Type -> Add New...

Set the checkbox in the dialog box to:

External type reference

as well as your type:namespace.MyEnum

Then add columns of this type to your tables.

Make sure there is no misunderstanding between the enum type from the model and the (external) enum type from your code as you're probably going to modify the current model. The best course of action would be to delete the previously constructed enum type from the model and change the columns to utilize the corresponding enum type from your code.

Your enum type can now be declared with the description attributes you intended.

4/24/2015 5:23:52 PM

Popular Answer

Enums don't require workarounds, so stop doing that. The most recent version of Entity Framework supports them.

You can utilize attributes to make your enums compatible with your website. Here is an example attribute:

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

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

Give your enums the following attribute:

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

Add extras to make it possibleToDescription() 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();


var blabla = DaylightSavingTime.Auto;


Automatically discover

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow