Is there a way to map a property to a custom type in Dapper?

Viewed 1571

We are looking at Dapper to simplify our mapping logic. It looks pretty promising except for one thing. We use custom types for our ids. For example:

public class MyEntityIdentity 
{
    public int IdentityValue { get; }
    public MyEntityIdentity(int identity) { IdentityValue = identity; }
}

public class MyEntity
{
    public MyEntityIdentity Identity { get; set; }
    int Prop1 { get; set; }
    string Prop2 { get; set; }
    bool Prop3 { get; set; }
}

With the SQL table looking something like:

create table [dbo].[MyEntity] (
    my_entity_id int identity(1,1) NOT NULL,
    prop1 int NULL,
    prop2 varchar(100) NULL,
    prop3 bit NOT NULL

    CONSTRAINT PK_MyEntity PRIMARY KEY CLUSTERED (my_entity_id ASC)
)

How can we map the "Identity" property?

1 Answers

You could use custom type handler like this:

public class IdentityHandler : SqlMapper.TypeHandler<MyEntityIdentity>
{
    public override MyEntityIdentity Parse(object value)
    {
        return new MyEntityIdentity((int)value);
    }

    public override void SetValue(IDbDataParameter parameter, MyEntityIdentity value)
    {
        parameter.Value = value.IdentityValue;
    }
}

And register it like this:

SqlMapper.AddTypeHandler(new IdentityHandler());
Related