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

て烟熏妆下的殇ゞ 提交于 2019-12-11 02:05:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9334365/change-dapper-so-that-it-maps-a-database-null-value-to-double-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!