Decorating an enum on the EF object model with a Description attribute?

c#, entity-framework, entity-framework-5

Solution

In the end I came up with a much simpler solution: I just used an extension method to get the description of the enum. That also made it a lot easier for localization, so I could use a Resource string.

public static string Description(this PrivacyLevel level) {
  switch (level) {
    case PrivacyLevel.Public:
      return Resources.PrivacyPublic;
    case PrivacyLevel.FriendsOnly:
      return Resources.PrivacyFriendsOnly;
    case PrivacyLevel.Private:
      return Resources.PrivacyPrivate;
    default:
      throw new ArgumentOutOfRangeException("level");
  }
}

Problem

I have defined an enum in my Entity Framework 5 model, which I'm using to define the type of a field on a table, e.g. ``` public enum PrivacyLevel : byte { Public = 1, FriendsOnly = 2, Private = 3, } ``` And I have a table `Publication` that has a `tinyint` field `PrivacyLevel`, which I've mapped in the EF model to use the `PrivacyLevel` type defined above, using the method described here. But I also want to be able to display a string description for each value of the enum. This I've done in the past for enums by decorating them with a Description attribute, e.g. ``` public enum PrivacyLevel : byte { [Description("Visible to everyone")] Public = 1, [Description("Only friends can view")] FriendsOnly = 2, [Description("Only I can view")] Private = 3, } ``` I've got some code that converts enums to strings by checking if they have a Description attribute, and that works well. But here, because I had to define the enum in my model, the underlying code is auto-generated, and I don't have anywhere stable to decorate them. Any ideas for a workaround?

Original source

Related problems