Skip to content

Suggestion for mapping non-standard Enums #694

@nCubed

Description

@nCubed

I had posted issue #448 in Feb-2016 where we had implemented our own method for parsing enums; when we upgraded from VS 2013 to VS 2015 (Roslyn), our custom enum parsing implementation failed (see issue #448). We do have a work-a-round in our current code base. With the other issues related to Enum parsing (#259, #458) and the planned support for V2 with issue #688, I thought I'd suggest a fairly non-invasive method for allowing a custom implementation of mapping Enums.

Note: I had originally forked the repo and tried to create a pull request, but I could not get VS 2015 to compile w/o errors before any changes.

Suggested Change to Support Enum Mapping

SqlMapper.Settings

// add new property
public static Func<Type, string, bool, object> EnumParse { get; set; }

public static void SetDefaults()
{
    CommandTimeout = null;
    ApplyNullValues = false;
    // set up default value
    EnumParse = Enum.Parse;
}

SqlMapper

// delete the enumParse field and update the usage 
// to consume the SqlMapper.Settings.EnumParse property:
il.EmitCall(OpCodes.Call, SqlMapper.Settings.EnumParse.Method, null)

Usage
To override the default Enum.Parse method, set the SqlMapper.Settings.EnumParse property prior to any dapper calls:

Func<Type, string, bool, object> enumParse = ( type, value, flag ) => ToEnum( type, value );

SqlMapper.Settings.EnumParse = enumParse;

private static object ToEnum( Type type, string value )
{
    // evaluate and return the result
    return result;
}

Would something like this be an option for the dapper team to consider?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions