Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum typed properties in Entity Framework entities?

Is there a way I can map generated entities to enum?

And what I mean is simple:

class Person
{
    RelationshipStaus RelationshipStatus { get; set; }
}

enum RelationshipStatus : byte
{
    Single,
    Married,
    Divorced
}

The property RelationshipStatus in the DB is a simple byte, I want that in my project it should be an enum.

like image 307
Shimmy Weitzhandler Avatar asked Dec 19 '25 08:12

Shimmy Weitzhandler


1 Answers

Unfortunately, you can't, at least not directly. For convenience, you can create an accessor that converts the value to and from the enum type:

public int RelationshipStatusInt { get; set; }

public RelationshipStatus RelationshipStatus
{
    get { return (RelationshipStatus)RelationshipStatusInt; }
    set { RelationshipStatusInt = (int)value; }
}

However you won't be able to use that properties in Linq to EF queries, because it won't be mapped to a DB column (but you can use it in Linq to Objects queries).

Another solution is described here, but it feels a bit awkward...

like image 169
Thomas Levesque Avatar answered Dec 21 '25 03:12

Thomas Levesque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!