Mapping enums while using dapper

dapper enums

Question

I have the following problem. I am using Dapper to connect to a database, the field that is a varchar in the database is an enum in my object. There is no problem for Dapper to map the database object to my DTO if the enum has the same name as the string in the database. Unfortunately, the strings in the database are not very user friendly and I was wondering if there is a way to map them or convert (only enums) to use more user friendly versions. For example, database value for a field:

SomeVeIRdLooking_Value

And I would like it to map to:

public enum MyEnum {
    MyFormattedValue
}

Popular Answer

You can select string values from database and convert it by hand.

    public enum MyEnum
    {
        None,
        Success,
        Failure
    }

    var enums = connection.Query<string>("select 'None' union select 'Success' union select 'Failure'")
            .Select(x => Enum.Parse(typeof (MyEnum), x)) //use your own method to parse enum from string
            .ToList();


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why