EF 6 - Can an option be set to store Enums as Strings?

Topics: General
Jul 25, 2013 at 11:05 PM
Hi

One feature I really like in Nhibernate is that it stores Enums as strings. If you have to quickly look at the raw data in the database it is so much nicer seeing a string then the "int" value of that enum option.

Does EF 6 support this?

I am using code first? I am currently using alpha 3 but I just noticed there is a new beta version.
Coordinator
Jul 26, 2013 at 1:03 AM
Edited Jul 26, 2013 at 1:04 AM
Hello chobo2,

No EF6 does not support mapping enums to string columns. We have a feature in our backlog that is about allowing type conversions and other property level transformations in the mapping that will hopefully enable this in the future. You can vote for it here:

http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2639292-simple-type-mapping-or-mapped-type-conversion-sup

Thanks,
Diego
Mar 3 at 7:22 PM
There is much more to using strings to store enums than the ability to look at raw data. If you wish to change the order of enum values or add a value to the list you are stuck when using ints. This should be a much higher priority than the more generic type conversion feature.
Mar 5 at 3:24 PM
Edited Mar 5 at 3:27 PM
Yes you can do it, but its hackery. I used the same hackery on EF4 to be able to use enums, though i stored as int (somewhat easier).
public enum Quantity : int
    {
        None = 0,
        Few = 1 << 0,
        Some = 1 << 1,
        Bunch = 1 << 2
    }

    public class SomeClass
    {
        protected internal string AppleQuantity { get; set; }
        [NotMapped]
        public Quantity Apples
        {
            get
            {
                var val = (Quantity)Enum.Parse(typeof(Quantity), AppleQuantity);
                return val;
            }
            set
            {
                AppleQuantity = value.ToString();
            }
        }
    }