Saving an array of enums in Entity Framework Code First


The other day I had an interesting thing to do, as the title said, I wanted my model to store an array of enum values. EF doesn’t map this kind of properties to anything, but you can create a new property that simulates it in your POCO entity.

This is what I did.

I had my entity expose a property that handles serializing and deserializing the real mapped property, so Days would be used by my code, while DaysInternal_do_not_use would only be used by Entity Framework.

As you can see, the Days handles the serialization with a bit of custom logic (could also have used a Json Serializer), the real property is written in a way that even an idiot could see that he shouldn’t use. Unfortunatly the EditorBrowsableState.Never seems not supported anymore since VS2015 (you can help here) but I added it for compatibility reasons. This attribute should prevent the property from being listed by Intellisense and doing so help prevent its use.

This way SQL Server only sees a string, but my code can use a model closer to my domain.

Author: Maurizio Pozzobon

Maurizio has 5+ years developing solutions in the insurance industry. He is passionate about doing the right thing right, so he works in a tight loop with his clients to deliver the best solution possible.