EF 4.1 Code First - map enum wrapper as complex type

后端 未结 4 1242
误落风尘
误落风尘 2020-12-24 08:25

I\'m trying to build a generic solution to the problem of enums with EF 4.1. My solution is basically a generic version of How to fake enums in ef 4. The enum wrapper class

4条回答
  •  离开以前
    2020-12-24 09:19

    I got Nathan generic enum wrapper class to work by simply making it abstract and move:

    public static implicit operator EnumWrapper  (TEnum e)
    

    to the derived classes like this:

    public class CategorySortWrapper : EnumWrapper
    {
        public static implicit operator CategorySortWrapper(CategorySort e)
        {
            return new CategorySortWrapper() { Enum = e };
        }
    }
    
    public abstract class EnumWrapper where TEnum : struct, IConvertible
    {
        public EnumWrapper()
        {
            if (!typeof(TEnum).IsEnum)
                throw new ArgumentException("Not an enum");
        }
    
        public TEnum Enum { get; set; }
    
        public int Value
        {
            get { return Convert.ToInt32(Enum); }
            set { Enum = (TEnum)(object)value; }
        }
    
        public static implicit operator int(EnumWrapper w)
        {
            if (w == null)
                return Convert.ToInt32(default(TEnum));
            else
                return w.Value;
        }
    }
    

    in my code I just using the it like this

    public CategorySortWrapper ChildSortType { get; set; }
    
    category.ChildSortType = CategorySort.AlphabeticOrder;
    

    I didn't do anything else and EF 4.1 created a "ComplexType like field" in the database named ChildSortType_Value

提交回复
热议问题