EF 4.1 Code First - map enum wrapper as complex type

后端 未结 4 1244
误落风尘
误落风尘 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:21

    There's a much simpler way to map enums in EF 4: just create an int property on your ChickenSandwich class to represent the int value of the enum. That's the property that EF should map, then have a "mini wrapper" property to allow you to use the enum

    public class ChickenSandwich 
    {   
        public int ID { get; set; }
        public string Name { get; set; }
    
        // This property will be mapped
        public int CheeseColorValue { get; set; }
    
        public Color CheseColor
        {
            get { return (Color) CheeseColorValue; }
            set { CheeseColorValue = (int) value; }
        }
    }
    

    I actually don't have to use the Fluent API or any kind of attribute decoration for this to work. On generating the database, EF will happily ignore any type it doesn't know how to map, but the int property will be mapped.

    I have tried mapping enums based on that article too, but it caused me no end of headaches. This method works well, and you could adapt your solution to use your wrapper as the "mapping" property, i.e. CheeseColor in this case.

提交回复
热议问题