Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace an Int property with an Enum in Entity Framework?

I have an entity class that has a property with an underlying db column of datatype Int, however in reality I want this property to be an Enum. Is there any way to specify that this property returns an Enum?

like image 324
flesh Avatar asked Dec 09 '08 15:12

flesh


People also ask

What are the value converters in EF?

What Is A Value Converter? When dealing with EF Core data modeling, we may store data differently than how we handle it within the context of our application. We can use value converters to optimize database storage, write performance, and read latency, in addition to optimizing memory in our application.


1 Answers

Indirectly, like so.

Personally, I leave the storage int public (for example as DbFoo, where the enum property is Foo) - that way I can still write lambdas against the column for execution at the DB, for example:

where row.DbFoo == SomeConstant

If you don't expose the storage value, you can't do this as cleanly. You could equally leave it internal, and have some methods in the context to do the filtering... here's one I wrote earlier today:

public IOrderedQueryable<User> Administrators
{
    get { return Users.Where(x => x.DbUserType == User.UserTypeAdmin)
             .OrderBy(x => x.Name);
}

where User.UserTypeAdmin is my internal constant. In this case, I couldn't use a discriminated subclass, as it was interfering with ADO.NET Data Services.

like image 167
Marc Gravell Avatar answered Sep 28 '22 00:09

Marc Gravell