In Julie Lerman's comprehensive book Programming Entity Framework 2nd Edition, she mentions that Enums are not supported in the Entity Framework. See the sidebar on page 280. I emailed her about it with a suggestion that the problem could be solved with extension methods. She liked the idea and suggested that I blog about it, but since I don't have a blog, here it is.
The situations where it's preferable to use Enums over 'magic numbers' or constants are legion and not limited to Entity Framework.
This solution I put together quite quickly is a set of extension methods for Enum, however I recognise that there may be a better way of doing things that covers all integral values more efficiently
I've created a Visual Studio 2010 project that covers Enums of type Byte, Short, Integer and Long, but the most likely candidtate will be Integer so let's take a look at that:
<Extension()>
Public Function ToIntegerValue(ByVal objEnum As [Enum]) As Int32
Dim objEnumType As Type = [Enum].GetUnderlyingType(objEnum.GetType)
If objEnumType.FullName = "System.Int32" Then
Return CInt([Enum].Parse(objEnum.GetType, objEnum.ToString))
End If
Return Nothing
End Function
It's fairly self evident what is going on. Having established the underlying type, the method parses the value.
Download the VS 2010 solution for all the exensions. All the bin and obj folders have been removed so it will need compiling before use.
2012 © Caz Limited