Dapper
Dapper copied to clipboard
support for enum type of db /支持 数据库 enum
hello there,
here we have an entity like this:
public enum ContentType
{
TXT,
MD,
HTML
}
[Table("card")]
public class Card: BaseEntityUInt64
{
[Column("uid")]
public ulong UID { get; set; }
[Column("create_at")]
public DateTime CreateAt { get; set; }
[Column("title")]
public string Title { get; set; }
[Column("content")]
public string Content { get; set; }
[Column("content_type")]
public ContentType ContentType { get; set; }
public Card()
{
this.Title = string.Empty;
this.Content = string.Empty;
this.ContentType = ContentType.TXT;
}
}
and the table defines like :
CREATE TABLE `card` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'IDæå¡ä¸å¿è·åIDï¼ä»¥ä¾¿å°æ¥ååº',
`uid` bigint(20) DEFAULT NULL,
`create_at` datetime DEFAULT NULL,
`title` varchar(128) DEFAULT NULL,
`content` text,
`content_type` enum('TXT','MD','HTML') NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
we want to support enum type for database, via TypeHandler:
public class EnumTypeHandler<T> : SqlMapper.TypeHandler<T> where T : struct, IConvertible
{
static EnumTypeHandler()
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumeration type");
}
}
public override T Parse(object value)
{
return (T)Enum.Parse(typeof(T), Convert.ToString(value));
}
public override void SetValue(IDbDataParameter parameter, T value)
{
parameter.Value = value.ToString();
parameter.DbType = DbType.AnsiString;
}
}
we use
SqlMapper.AddTypeHandler(typeof(ContentType), new EnumTypeHandler<ContentType>());
but it doesn't work.
so I forked the repository and made a little change.
please consider this.