Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper enum mapping

Tags:

.net

dapper

I need help for mapping enums with Dapper and Oracle.

I have a field in Oracle type NUMBER (1) and must turn into an enum in my entity.

public Status Status { get; set; }

Status is a enum:

public enum Status
{
    [Description("Inactive", "0")]
    Inactive = 0,

    [Description("Active", "1")]
    Active = 1,
 }

How to make the mapping using Dapper?

like image 254
Marcelo Dias Avatar asked Apr 25 '16 12:04

Marcelo Dias


3 Answers

Enums should JustWork™ for either integer or string representations. If it isn't working, you'll have to be more specific about any exception that it is throwing. For example, thinking aloud and pure speculation, but: IIRC Oracle has a habit of wanting to treat numbers as 64-bit, and I wonder if the enum mapping code handles all flavors of numeric conversion. If it doesn't, then that's a bug.

So: does it work?

like image 82
Marc Gravell Avatar answered Nov 14 '22 06:11

Marc Gravell


Just to be explicit with the sound advice in the other answers. Your database might have the data stored in a column called StatusId whereas you object's property might simply be Status.

I typically get around this by using an alias in the SQL query:

SELECT StatusId AS Status FROM Table

Dapper implicitly understands how to map an int database field to a C# enum. I usually give my enums explicit values to make things as clear as possible, e.g.

public enum Status
{
   Active = 1,
   Inactive = 2
}
like image 32
Pseudonymous Avatar answered Nov 14 '22 08:11

Pseudonymous


I have not been able to get nullable enums to work when using dapper.

To get around this I create two classes: an object model and a SQL model.

The SQL model is a simple version of the object model, with enums as the strings by which they are saved in the database. The object model has a constructor taking a SQL model as input.

class ThingSQLModel
{
    public int? Id;

    public String? ThingType;

 ....


}

class Thing
{
    public int? Id;

    public EnumThingType? ThingType{ get; set; }

 ....

    public Thing(ThingSQLModel)
    {
        Id = output.Id;

        ThingType= EnumHelper.TryParseNullable<EnumThingType>(output.ThingType);
    }
}

for TryParseNullable<EnumThingType> see : Parsing value into nullable enumeration

Perhaps there is a better approach by explicitly overriding the default parsing for this type? hmm. I'll experiment and comeback with an answer.

like image 1
compound eye Avatar answered Nov 14 '22 07:11

compound eye