CTICoder

A random spillage of programming (and other) thoughts

  • Welcome!

    Enjoy the random thoughts, but only if you really want to.
  • a

  • Archives

Using Enums with Entity Framework

Posted by Michael Bray on August 16, 2008

I was a bit disappointed (but not surprised) to see that EF didn’t seem to support Enum types on the entities it generates.  Even if you try to manually change the type to an enum type defined in your project, it will complain saying that it can’t find the type.  (Maybe I’m just not doing it right??)

Anyway, there is a seemingly elegant solution… utilize the fact that the entity classes are partial.

For example, if you have an enum:

public enum AccountType
{
    Internal,
    Public,
    External
}

that you want to store in the database (say as part of an ‘Account’ object) then you can just extend the partial ‘Account’ class and change a few properties in the .edmx file… Personally, I would rather have the C# class maintain the naming conventions than the database fields, so in this example I name the field in the database with a ‘t’, to indicate that it is a ‘type’. You could use anything – ‘e’ for ‘enum’, or even ‘enum’ all the way. So for example:

image

Then in the properties of the ‘tAccountType’ field, set the Getter and Setter to ‘private’:

image

And finally, add a class to your code that extends the partial class:

public partial class Account
{
    public AccountType? AccountType
    {
        get { return (AccountType)this.tAccountType; }
        set { this.tAccountType = (int?)value; }
    }
}

…and voila… the class now provides the enum the way it should, and still manages the underlying entity.

4 Responses to “Using Enums with Entity Framework”

  1. That’s good stuff. Funny how I found this answer when searching on Google.

  2. [...] info Published okt 07 2008, 09:50 by Jo-wen Filed under: Entity Framework [...]

  3. Craig said

    Can you use this property in LINQ queries?

  4. aragon said

    You example is great but unfortunatly it doesn’t work inside a linq query

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>