I am using Entity Framework 5, DB first. I know how to define an enum on my model, and set the type of a field to that enum.
Now, I have a requirement to map a field MyField
to an enum that is defined externally, i.e. not in the EF model (OtherNamespace.MyEnum
). The designer does not allow me to set the type to anything outside the model. I tried editing the edmx file manually, but that causes an error:
Error 10016: Error resolving item 'MyField'. The exception message is: 'Unresolved reference 'OtherNamespace.MyEnum'.'.
OtherNamespace.MyEnum
is referenced by my project.
How do you do it?
This can be done, but it requires a little sacrifice on the database side. Entity Framework (5 onwards) supports mapping a field to an enumeration, but only for
byte
,sbyte
,short
,ushort
,int
,uint
,long
, orulong
types.Assume that we have the following sample table:
Title
has been declared as an integer. In a real database, this might be a foreign key over to aTitleTypes
table.Also, let's assume that the external enumeration that we are going to be tying into is defined as:
If we import the
People
table into an EDMX we can right click on theTitle
column and Convert to EnumThis will bring up a dialog box allowing us to specify a name for the enumeration in the EDMX ModelStore, define any values for the enumeration OR link to an external enumeration via Reference external type.
Give it a Type Name of
TitleEnum
, check Reference external type, and typeEnumerations.TitleEnum
in the provided field. Click OK and it will associate the column to the external enumeration.Note:
Now, when we create a new person we can utilize the enumeration and it will be translated into its Int representation.