Sometimes, I actually prefer to store letters for rather than integers in the database. Yes, it can be less performant (as you do need to implement a custom converter), but can make the database a lot easier to read. Consider the example below that TradeDirection
. It might be more preferable to see B
and S
in the database which is more readable instead of using 1
and 2
for Buy
and Sell
which is somewhat meaningless.
1 2 3 4 5 |
public enum TradeDirection { Buy = 1, Sell = 2 } |
In the code, it usually doesn't matter what numbers are behind the enum, so the ints
(32-bits) can be replaced with chars
(16-bits).
1 2 3 4 5 |
public enum TradeDirection { Buy = 'B', Sell = 'S' } |
Below you can find 4 simple extensions methods on enum
, string
, and PropertyBuilder
that enable that enum to letter conversion with one line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public static string ToLetter(this Enum enumValue) { return ((char)Convert.ToInt32(enumValue)).ToString(); } public static T ToEnum<T>(this string value) where T : struct, IConvertible { return (T)Enum.ToObject(typeof(T), Convert.ToInt32(value[0])); } public static PropertyBuilder<TEnum> StoreAsCharacter<TEnum>(this PropertyBuilder<TEnum> builder) where TEnum : struct, Enum { return builder.HasConversion(x => x.ToLetter(), x => x.ToEnum<TEnum>()).HasMaxLength(1); } public static PropertyBuilder<TEnum?> StoreAsCharacter<TEnum>(this PropertyBuilder<TEnum?> builder) where TEnum : struct, Enum { return builder.HasConversion(x => x == null ? null : x.ToLetter(), x => x == null ? (TEnum?)null : x.ToEnum<TEnum>()).HasMaxLength(1); } |