Does Dapper support custom types on stored procedure parameters?

Dav*_*eny -1 c# dapper

If I have a custom type (in my case, a Date class), is it possible to have Dapper automatically handle the type conversions when setting up stored procedure parameters? At the moment, I have to do this:

public void Execute(Date value)
{
    var parameters = new DynamicParameters();
    parameters.Add("MyDate", Date.ToDateTime(), DbType.Date);
    Execute("dbo.InsertDate", parameters, CommandType.StoredProcedure);
}
Run Code Online (Sandbox Code Playgroud)

Do I really have to convert it to a more recognised system type? I was hoping that Dapper's TypeHandler code would work, but it seems to be ignoring it, so I am assuming that it is only for handling projections when retrieving data, not for parameterising commands.

This is using Dapper 1.60.0 on .NET Framework 4.7.2

ste*_*351 5

是的,Dapper确实支持对存储过程参数的类型进行自定义处理。这是一个自定义Date类转换的工作示例:

// only required once per app-domain, unless SqlMapper.ResetTypeHandlers() is called
SqlMapper.AddTypeHandler(typeof(Date), new DateHandler()); 

DynamicParameters parameters = new DynamicParameters();
parameters.Add("MyDate", new Date() { MyDate = DateTime.Today });

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    connection.Execute(
        sql: "dbo.InsertDate", 
        param: parameters, 
        commandType: CommandType.StoredProcedure);
}
Run Code Online (Sandbox Code Playgroud)

这是处理给的转换的类SqlMapper.AddTypeHandler。对于设置存储过程参数,这SetValue很重要。

public class DateHandler : ITypeHandler
{
    public object Parse(Type destinationType, object value)
    {
        return new Date() { MyDate = (DateTime)value };
    }

    public void SetValue(IDbDataParameter parameter, object value)
    {
        parameter.DbType = DbType.Date;
        parameter.Value = ((Date)value).MyDate;
    }
}
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这是需要自定义处理的自定义类。

public class Date
{
    public DateTime MyDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)