Dapper Read SqlHierachyId Column (SQL Server 2008 R2)

.net c# dapper sql-server

Question

I'm trying to read from a SQL Server 2008 R2 database that contain columns of the SQL Server hierarchyid type (aka SqlHierachyId).

I want to use this this class with Dapper:

public class Foo 
{ 
    public int Id { get; set; }
    public SqlHierarchyId Path { get; set; }
} 

eg: connection.Query<Foo>("select 3 as [Id], hierarchyid::Parse('/1/2/3/') as [Path]");

(Note for Testing, you need to reference Program Files (x86)\Microsoft SQL Server\110\Shared\Microsoft.SqlServer.Types.dll to be able to use SqlHierarchyId)

If I run this, I get a DataException exception: Error parsing column x (Path=/1/2/3/ - Object)

I've tried adding an ITypeMap via and setting breakpoints on all the interface methods to see what values it gets passed - but it never gets called.

Any suggestions on how I can get Dapper to let me specify a custom mapper? (Alternatively, if there's an extension that supports all the Sql types, that'd be good too)

Accepted Answer

Dapper 1.34 has support for SqlHierarchyId in the core library; it should now just work.


Popular Answer

Dapper does support SqlHierarchyId but you will still get the exception if you are using the latest Microsoft.SqlServer.Types Nuget package. To make it work, add this to your web.config or app.config:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
       <assemblyIdentity name="Microsoft.SqlServer.Types" publicKeyToken="89845dcd8080cc91" culture="neutral" />
       <bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why