简体   繁体   中英

Dapper: Converting a string to an enum

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM