Change Dapper so that it maps a database null value to double.NaN

.net ado.net dapper sqlite

Question

I have a nullable double column in my SQLite database.

When reading from the database (for columns of type double) I would like to convert nulls into "double.NaN".

Currently dapper sets null values to 0, which I do not want.

What are my options?

  1. Modify Dapper source code.
  2. Can't use Dapper, need to write my own ADO.NET code the old fashioned way?
  3. change the way that I call the cnn.Query method, to modify the way that mapping happens.

My first choice is option 1, but I need help modifying Dapper.

Accepted Answer

Personally, I will advise against this; a null is not quite the same thing as NaN. If you really want to do this, you would have to look at GetTypeDeserializer. The code to do this is generated dynamically using ILGenerator, and is fairly complex. If you look for a line:

il.MarkLabel(isDbNullLabel); // incoming stack: [target][target][value]

this is where the code branches to if a DbNull is detected. What it does currently is simply pop the two values (the value and the target) from the stack, drop them on the floor, and carry on. You would need to check for float/double as a special case, apply your conversion, then assign the NaN to the member.

I repeat my claim, though, that this simply isn't a valid thing to do. A much simpler option would be:

public double? Value {get;set;}

which requires zero changes, and will work currently. If you really really want it treated as a non-nullable double, maybe:

private double foo = double.NaN;
public double Foo { get { return foo; } set { foo = value; } }

this will now default to NaN, and materialize correctly when there are values.




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