gpt4 book ai didi

c# - Dapper 和枚举作为字符串

转载 作者:太空狗 更新时间:2023-10-29 21:26:46 24 4
gpt4 key购买 nike

我正在尝试使用 DapperDapper-Extensions 并将我的 enums 在数据库上序列化为 string.

现在它们被序列化为整数(在 VARCHAR 字段中)。

有什么办法吗?我可以添加任何自定义类型映射吗?

如果我无法解决这个问题,我可能需要回到 EF..

最佳答案

有一种方法,我认为它更健壮和干净。

我提供的解决方案适用于任何枚举,但它涉及一些额外的编码。它还涉及在 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());

现在您可以简单地将国家/地区用作“枚举”。例如:

public class Address
{
public string Street { get; set; }
public Country Country { get; set; }
}

var addr = new Address { Street = "Sesamestreet", Country = Country.GB };

缺点当然是枚举在内存中不是由整数而是字符串支持的。

关于c# - Dapper 和枚举作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37264655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com