Dapper: Converting a string to an enum

.net c# dapper

Question

I'm new to Dapper and I'm trying to figure out if it can handle mapping database strings to enums; it doesn't happen for me by default.

For example, say I use this SQL

select customer_type from customers

and this class

public class Customer
{
    ...
    public CustomerType CustomerType { get; set; }
    ...
}

with this enum

public enum CustomerType
{
     Unknown,
     SomeCustomerType,
     ...
}

In this case I always end up with the default enum value (Unknown) rather than a mapping of the string value from the database.

Anyone know how I can achieve this?

Edit: I know that this is possible with an number field because an number will convert to an enum, but that has the drawback of having to ensure that the database id and enum are kept in sync. I'm looking for something similar but with string.

Popular Answer

If you alias the column name to have the same name as your property that should work too:

SELECT REPLACE(customer_type, ' ','') As CustomerType FROM customers

You can also use the replace function to remove white spaces in case the values for the customer_type field in the database has any.



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