I've just started using Dapper.Contrib to help me with inserts and gets but since my enums are stored as strings in the database (for several reasons) I'm having trouble with inserts. Dapper works seamlessly with string enums when reading, but inserts will always put the ordinal value into the database.
I've read many proposals to Dapper for that, and quite a few issues opened but didn't find a working solution. My simplified class looks like the following:
public class Person {
public long Id { get; set; }
public string Name { get; set; }
public Gender Gender { get; set; }
}
public enum Gender { Female, Male, TransWoman, TransMan }
I was expecting I could configure Dapper.Contrib to issue Inserts using enum names instead of ordinal values, so that the code bellow would magically work and insert 'Male' in the varchar(20) database field Gender:
void InsertPersonFelipe(SqlConnection conn) {
var person = new Person { Name = "Felipe", Gender = Gender.Male };
conn.Insert(person);
}
Is there a way to add custom mapping for typeof(Gender)
?
Or, better yet, does Dapper.Contrib provides a configuration to make it use enum names instead of their ordinal values?
I've written an extension method to handle translating the enum into a string and takes into account the Table and Computed attributes in Dapper.Contrib. You could just as easily take these out if you didn't want to reference Dapper.Contrib.
Usage:
Extension method: