Reputation: 38083
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).
Upvotes: 4
Views: 2089
Reputation: 2361
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.
Upvotes: 5