Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Ability to handle nulls in a custom type handler

Open jonnymuir opened this issue 3 years ago • 2 comments

In https://sodocumentation.net/dapper/topic/13/handling-nulls it states that nulls are handled as follows:

"values read that are null are presented as null, or (in the case of mapping to a known type) simply ignored (leaving their type-based default)"

Propose using the same pattern as ITypeHandlerParse to implement a INullTypeHandler to allow us to handle a null rather than being ignored. If not implemented this will then have no effect and therefore be safe / backwards compatible / no risk and have no runtime performance overhead.

The scenario this is useful for is if a user wants to differentiate between:

  • A column being present in the result set but null
  • A column not being present in a result set

An example of this would be implementing an Optional pattern

Below is a .net fiddle to demonstrate.
DotNetFiddle example

jonnymuir avatar Feb 08 '22 20:02 jonnymuir

Summary of pull request:

Allow a developer to implement an additional interface (INullTypeHandler) on a custom type handler.

Performance assessment:

Performance overhead = 1 check for INullTypeHandler per mapped ITypeHandler type on generation of IL. No performance overhead at runtime of IL (because the generated IL is the same if the interface isn't implemented) If Interface is implemented the same pattern as ITypeHandlerParse is used

Impact assessment:

Developer is required to implement a new interface. No change to any existing behaviours.

jonnymuir avatar Mar 10 '22 13:03 jonnymuir

Hi good dapper people - we have been using this now in development and UAT since March and are about to put it into live. It is a really useful addition for us. Dapper is by far the best fit for our projects and this addition is critical for our solution.

It would be great it this addition could be a candidate to be a pull requested, I think there may be others that find it useful and I think it fits with the ethos of the project (performance, simplicity and quality!)

Is there anything I can do to make it more attractive? Contribute to documentation etc?

Ta.

jonnymuir avatar Jun 16 '22 07:06 jonnymuir