Entity Framework 4.1 – Supporting Enums

One of those features you think are so trivial are hard to miss if you use that latest new tool. One of those is enum support in Entity Framework 4.1, just like in all other versions of the framework it just isn’t there.

There is though a way to get around it, unfortunately it does mean changing your model just a tiny bit.

In the sample class model I used for my previous posts on mapping inheritance each movie had an enum value to hold its media type, DVD, Bluray,…

You won’t see it mapped by default in your database if you use Entity Framework 4.1 out of the box. So having the enum property there isn’t enough, you have to explicitly add an int property like below.

[Required]
public virtual EMediaType MediaType { get; set; }
 
public virtual int MediaTypeId
{
    get { return (int)MediaType; }
    set { MediaType = (EMediaType)value; }
}

And change your model mapping a bit inside your DbContext class if needed.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<Movie>()
        .Property(x => x.MediaTypeId)
        .HasColumnName("MediaType")
        .IsRequired();
 
    base.OnModelCreating(modelBuilder);
}

You can still use the enum property in the rest of your application, which I encourage.

5 Replies to “Entity Framework 4.1 – Supporting Enums”

  1. This is a nice solution, but have you found a way to be able to do this:

    from foo in ctx.Foos
    where foo.MediaType == MediaType.Bar
    select foo

    Without being able to do this, there’s not really a need to add 2 properties instead of one IMO.

  2. Interesting, unless I can tweak the generated expression I’m afraid not. But I’ll look into it when I have some time.

Leave a Reply

Your email address will not be published. Required fields are marked *