Dapper.NET

Type Handlers

Remarks#

Type Handlers allow database types to be converted to .Net custom types.

Converting varchar to IHtmlString

public class IHtmlStringTypeHandler : SqlMapper.TypeHandler<IHtmlString>
{
    public override void SetValue(
        IDbDataParameter parameter, 
        IHtmlString value)
    {
        parameter.DbType = DbType.String;
        parameter.Value = value?.ToHtmlString();
    }

    public override IHtmlString Parse(object value)
    {
        return MvcHtmlString.Create(value?.ToString());
    }
}

Installing a TypeHandler

The above type handler can be installed into SqlMapper using the AddTypeHandler method.

SqlMapper.AddTypeHandler<IHtmlString>(new IHtmlStringTypeHandler());

Type inference allows you to omit the generic type parameter:

SqlMapper.AddTypeHandler(new IHtmlStringTypeHandler());

There’s also a two-argument overload which takes an explicit Type argument:

SqlMapper.AddTypeHandler(typeof(IHtmlString), new IHtmlStringTypeHandler());

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow