EF5 Code First Enums and Lookup Tables

后端 未结 6 1743
南笙
南笙 2020-11-27 05:35

I\'d like to define an enum for EF5 to use, and a corresponding lookup table. I know EF5 now supports enums, but out-of-the-box, it seems it only supports this at the objec

6条回答
  •  感动是毒
    2020-11-27 05:54

    I have included this answer as I've made some additional changes from @HerrKater

    I made a small addition to Herr Kater's Answer (also based on Tim Abell's comment). The update is to use a method to get the enum value from the DisplayName Attribute if exists else split the PascalCase enum value.

     private static string GetDisplayValue(object value)
     {
       var fieldInfo = value.GetType().GetField(value.ToString());
    
       var descriptionAttributes = fieldInfo.GetCustomAttributes(
         typeof(DisplayAttribute), false) as DisplayAttribute[];
    
       if (descriptionAttributes == null) return string.Empty;
       return (descriptionAttributes.Length > 0)
       ? descriptionAttributes[0].Name
       : System.Text.RegularExpressions.Regex.Replace(value.ToString(), "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ");
     }
    

    Update Herr Katers example to call the method:

     command = string.Format("INSERT INTO {0} VALUES({1},'{2}');", enumType.Name, (int)enumvalue,
                                            GetDisplayValue(enumvalue));
    

    Enum Example

    public enum PaymentMethod
    {
        [Display(Name = "Credit Card")]
        CreditCard = 1,
    
        [Display(Name = "Direct Debit")]
        DirectDebit = 2
    }
    

提交回复
热议问题