I have an enum like:
public enum AccountStatus : byte
{
Locked = (byte)'L',
Active = (byte)'A',
Deleted = (byte)'D'
}
and would like to to store the char values in the database. Is there a way in Dapper with type maps or otherwise to define which enum types should be mapped to their char values (for read/update/insert)?
The anonymous type member declarator is also preventing me from casting the property to a char directly in the query:
As mentioned by @TyCobb in the comments, this isn't an issue with storing an Enum as a char, but rather with how anonymous type properties are declared.
Anonymous types can only infer and generate names for "simple property references" where no transformation is done to the property during assignment, such as
new { account.AccountStatus }
As soon as you transform the data or need to rename the property, you must explicitly declare the property name:
new { Status = (char)account.AccountStatus }
In regards to reads, you can map to a char
via dapper, then cast as your enum in your select (or transform the data in whatever way is most appropriate):
var result = connection.Query<char>(
"select char column from table where Status = @Status",
new {Status = (char)account.AccountStatus}
).Select(x => (AccountStatus)x).FirstOrDefault();
In addition, Dapper also handles AccountStatus : byte
cases natively, so you may be able to directly return the value as your enum:
var result = connection.Query<AccountStatus>(
"select char column from table where Status = @Status",
new {Status = (char)account.AccountStatus}
).FirstOrDefault();