Map string column in Entity Framework to Enum

.net c# database entity-framework orm

Question

Is there a way to map a string column to an enum in an Entity Model?

I have done this in Hibernate, but can't figure it out in EMF.

1
21
9/15/2011 10:03:49 PM

Accepted Answer

It is ugly, but for mapping enums to strings I found something like this:

public virtual string StatusString
{
    get { return Status.ToString(); }
    set { OrderStatus newValue; 
          if (Enum.TryParse(value, out newValue))
          { Status = newValue; }
        }
}

public virtual OrderStatus Status { get; set; } 

OrderStatus is the enumerator type, Status is the enumerator and StatusString is the string version of it.

13
9/15/2011 10:21:40 PM

Popular Answer

Probably a nicer version.

OrderStateIdentifier field is used for both JSON serialization and database field, while OrderState is only used in the code for convenience.

    public string OrderStateIdentifier
    {
        get { return OrderState.ToString(); }
        set { OrderState = value.ToEnum<OrderState>(); }
    }

    [NotMapped]
    [JsonIgnore]
    public OrderState OrderState { get; set; }


public static class EnumHelper
{
    /// <summary>
    /// Converts string to enum value (opposite to Enum.ToString()).
    /// </summary>
    /// <typeparam name="T">Type of the enum to convert the string into.</typeparam>
    /// <param name="s">string to convert to enum value.</param>
    public static T ToEnum<T>(this string s) where T: struct
    {
        T newValue;
        return Enum.TryParse(s, out newValue) ? newValue : default(T);
    }
}


Related Questions





Related

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