Colin O'Dell
Colin O'Dell

Reputation: 8647

Mapping database int to enum flags in model

My application has a model which currently uses an integer in the SQL database to store the value of a [Flags]Enum. The Enum looks something like this:

namespace MyProject.Models
{
    [Flags]
    public enum MyEnum : int
    {
        FirstThing = 1,
        SomethingElse = 2,
        YetAnotherOne = 4
    }
}

So if a particular row had this field set to 3, it means flags FirstThing and SomethingElse are both set. Right now I'm using a helper class to convert and check MyEnum values to/from/against the integer, which does work, but I think there's gotta be a way to map the SQL INT field directly to the enum.

Basically the end goal is to have a list of checkboxes, one for each possible flag that will eventually be saved in the database as an INT.

Is this a good idea? If so, how do I go about this? If not, should I just suck it up and write out all that code myself (instead of using some nifty tricks)?

Upvotes: 1

Views: 1834

Answers (1)

Femaref
Femaref

Reputation: 61437

You will need that helper class, neither OR mapper fully supports mapping int to enum. There are ways around it, but that's more of a replication of the target behaviour with gapping holes in it than anything near the wanted effect.

Upvotes: 2

Related Questions