有一种方法,我认为它更强大、更干净。
我提供的解决方案适用于任何枚举,但它涉及一些额外的编码。它还涉及在 Dapper 中添加自定义类型处理程序。但是,如果这个答案获得一些选票,我将更改 Dapper 源代码以在类型处理中自动包含此解决方案并请求拉取请求。
我实际上实现了这个解决方案并在生产中使用它。
开始。
首先是用作枚举的结构体(不是类,因为该结构体仅保存字符串引用):
public struct Country
{
string value;
public static Country BE => "BE";
public static Country NL => "NL";
public static Country DE => "DE";
public static Country GB => "GB";
private Country(string value)
{
this.value = value;
}
public static implicit operator Country(string value)
{
return new Country(value);
}
public static implicit operator string(Country country)
{
return country.value;
}
}
现在我们需要这个结构的类型处理程序
public class CountryHandler : SqlMapper.ITypeHandler
{
public object Parse(Type destinationType, object value)
{
if (destinationType == typeof(Country))
return (Country)((string)value);
else return null;
}
public void SetValue(IDbDataParameter parameter, object value)
{
parameter.DbType = DbType.String;
parameter.Value = (string)((dynamic)value);
}
}
在应用程序启动的某个地方,我们必须向 Dapper 注册类型处理程序
Dapper.SqlMapper.AddTypeHandler(typeof(Country), new CountryHandler());
现在您可以简单地使用 Country 作为“枚举”。例如:
public class Address
{
public string Street { get; set; }
public Country Country { get; set; }
}
var addr = new Address { Street = "Sesamestreet", Country = Country.GB };
当然,缺点是枚举在内存中不是由整数而是由字符串支持。