Dapper和Enums作为字符串

Mau*_*rGi 6 .net c# dapper dapper-extensions

我正在尝试使用Dapper和将数据库Dapper-Extensions序列化为.enumsstring

现在,它们被序列化为整数(在VARCHAR字段内).

有没有办法做到这一点?我可以添加的任何自定义类型映射?

如果我不能通过它,我可能需要回到EF.

nee*_*ohw 7

我认为有一种方法更可靠,更干净。

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

现在我们需要此结构的类型处理程序

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在启动应用程序的某个地方,我们必须向Dapper注册类型处理程序

Dapper.SqlMapper.AddTypeHandler(typeof(Country), new CountryHandler());
Run Code Online (Sandbox Code Playgroud)

现在,您可以简单地将Country用作“枚举”。例如:

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

var addr = new Address { Street = "Sesamestreet", Country = Country.GB };
Run Code Online (Sandbox Code Playgroud)

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

  • 显然,不为枚举调用 ITypeHandlers 是 Dapper 中长期存在的错误。https://github.com/DapperLib/Dapper/issues/259 (2认同)

Mau*_*rGi 6

感谢 Marc Gravell 的回复:

唯一的方法是手动进行插入。

还使用以下帖子:如何使用 Dapper 执行插入并返回插入的身份?

下面是我的解决方案。

请注意,自动选择工作:您可以直接使用 Dapper(扩展)GetList<T>,不需要映射到枚举。

public enum ComponentType
{
    First,
    Second,
    Third
}

public class Info
{
    public int Id { get; set; }
    public ComponentType InfoComponentType { get; set; }

    public static void SaveList(List<Info> infoList)
    {
        string ConnectionString = GetConnectionString();

        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();

            foreach (Info info in infoList)
            {
                string sql = @"INSERT INTO [Info] ([InfoComponentType]) 
                               VALUES (@InfoComponentType);
                               SELECT CAST(SCOPE_IDENTITY() AS INT)";

                int id = conn.Query<int>(sql, new
                {
                    InfoComponentType = info.InfoComponentType.ToString()
                }).Single();

                info.Id = id;
            }

            conn.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


sol*_*ish 6

我的技术与 neeohw 类似,但让我使用真正的枚举。而且它是通用的,所以我不必写很多次。

有一个不可变的结构体封装了枚举值。它具有单个属性和隐式转换,以及通用的自定义类型处理程序。

public readonly struct DapperableEnum<TEnum> where TEnum : Enum
{
    [JsonConverter(typeof(StringEnumConverter))]
    public TEnum Value { get; }

    static DapperableEnum()
    {
        Dapper.SqlMapper.AddTypeHandler(typeof(DapperableEnum<TEnum>), new DapperableEnumHandler<TEnum>());
    }

    public DapperableEnum(TEnum value)
    {
        Value = value;
    }
    public DapperableEnum(string description)
    {
        Value = EnumExtensions.GetValueByDescription<TEnum>(description);
    }

    public static implicit operator DapperableEnum<TEnum>(TEnum v) => new DapperableEnum<TEnum>(v);
    public static implicit operator TEnum(DapperableEnum<TEnum> v) => v.Value;
    public static implicit operator DapperableEnum<TEnum>(string s) => new DapperableEnum<TEnum>(s);
}

public class DapperableEnumHandler<TEnum> : SqlMapper.ITypeHandler
    where TEnum : Enum
{
    public object Parse(Type destinationType, object value)
    {
        if (destinationType == typeof(DapperableEnum<TEnum>))
        {
            return new DapperableEnum<TEnum>((string)value);
        }
        throw new InvalidCastException($"Can't parse string value {value} into enum type {typeof(TEnum).Name}");
    }

    public void SetValue(IDbDataParameter parameter, object value)
    {
        parameter.DbType = DbType.String;
        parameter.Value =((DapperableEnum<TEnum>)value).Value.GetDescription();
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用静态构造函数在启动时自动注册类型处理程序。

我使用 GetDescription / GetValueByDescription (与此答案相同的想法)来支持不是有效 C# 枚举值的字符串。如果您不需要此功能,ToString 和 Enum.Parse 也可以正常工作。

JsonConverter 属性使 Json.Net 也使用字符串值。当然,如果你不使用Json.Net,请将其删除

这是一个例子:

enum Holiday
{
    Thanksgiving,
    Christmas,
    [Description("Martin Luther King, Jr.'s Birthday")]
    MlkDay,
    Other,
}

class HolidayScheduleItem : IStandardDaoEntity<HolidayScheduleItem>
{
    public DapperableEnum<Holiday> Holiday {get; set;}
    public DateTime When {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

并且调用代码可以使用普通的枚举值。

        var item = new HolidayScheduleItem()
        {
            Holiday = Holiday.MlkDay,
            When = new DateTime(2021, 1, 18)
        };
Run Code Online (Sandbox Code Playgroud)

它适用于普通的 Dapper 或 Dapper.Contrib:

        await conn.ExecuteAsync("INSERT HolidayScheduleItem ([Holiday], [When])
           VALUES(@Holiday, @When)", item);
        await conn.InsertAsync(item);
Run Code Online (Sandbox Code Playgroud)

来自我的数据库:


小智 5

我无法获得ITypeHandler与 s 一起使用的建议enum。然而,我在分析 Dapper 生成的 SQL 时发现它将enum参数声明为int. 所以我尝试为该enum类型添加类型映射。

在应用程序启动时添加这个 Dapper 配置对我来说很有效。

Dapper.SqlMapper.AddTypeMap(typeof(MyEnum), DbType.String);
Run Code Online (Sandbox Code Playgroud)

然后我connection.Execute(updateSql, model)就照常使用。不需要使用.ToString()或任何其他显式转换。底层的列是varchar(20).

  • 这不起作用。 (2认同)