4

I've been using Linq2Sql for the last few years and got used to a few features, like having an int or tinyint field in the DB, that I redefine in the DBML file to be of enum type, so it's nice and convenient to run a SQL query directly comparing to the enum (see here for my question 3 years ago on the subject, and the answer there).

Now I'm starting a project using Entity Framework 5, and while EF seems to have gotten many things right that L2S didn't (e.g. detach/reattach), I'm dismayed to see that there doesn't seem to be any easy way to change the C# type of such a field to be an enum.

Has anyone found a way to do this cleanly, so that I could have a query like:

var q = entities.Things.Where(t => t.Status == TStatus.Closed);

(and no, I don't want to have to cast to int or byte inline).

Community
  • 1
  • 1
Shaul Behr
  • 36,951
  • 69
  • 249
  • 387

1 Answers1

5

Code First

EF5 Code First supports enum properties on .NET 4.5. The following entity will create a int field in the database:

public class Event
{
    public int EventId { get; set; }
    public Status Status { get; set; }
}

public enum Status
{
    Open,
    Closed,
    Pending
}

To which you could query:

db.Events.Where(e => e.Status == Status.Pending)

Database First

As explained in this post, here's how you accomplish the same thing for Database First.

Go to the model browser and create a new enum type, then go to whatever column you wish to use it on and change its type to the enum that you just created.

Community
  • 1
  • 1
Joey Gennari
  • 2,361
  • 17
  • 26
  • Please note that it'd work only on .net 4.5 (while EF5 also runs on earlier versions). – Sergei Rogovtcev Sep 11 '12 at 14:26
  • 2
    Found this question: http://stackoverflow.com/questions/11595008/enums-ef-5-0-database-first – Joey Gennari Sep 11 '12 at 14:34
  • I overheard that only difference in running EF5 CF between .net 4 and 4.5 is that in 4 it does not use new performance improvements – Goran Obradovic Sep 11 '12 at 14:54
  • 1
    @DanielHilgarth by design. [MSDN](http://msdn.microsoft.com/en-US/data/jj574253): "When targeting .NET **4.5** this release [EF 5] introduces some new features including **enum support**, table-valued functions, spatial data types and various performance improvements." – Sergei Rogovtcev Sep 11 '12 at 18:07
  • 1
    @GoranObradovic I am sorry to disappoint, but you overheard wrong. See link above. – Sergei Rogovtcev Sep 11 '12 at 18:08
  • @JoeGennari - thanks for the link - that answered the question! If you'll update your answer to show the solution for DB first, I'll give you answer credit. – Shaul Behr Sep 12 '12 at 09:01
  • Updated my answer with a Database First version. – Joey Gennari Sep 12 '12 at 11:09