更改 Dapper,以便将数据库空值映射到 double.NaN

发布于 2025-01-07 10:22:53 字数 309 浏览 0 评论 0原文

我的 SQLite 数据库中有一个可为空的双列。

从数据库读取时(对于 double 类型的列),我想将 null 转换为“double.NaN”。

目前 dapper 将 null 值设置为 0,这是我不想要的。

我有什么选择?

  1. 修改Dapper源代码。
  2. 无法使用 Dapper,需要以老式方式编写自己的 ADO.NET 代码吗?
  3. 更改我调用 cnn.Query 方法的方式,以修改映射发生的方式。

我的第一选择是选项 1,但我需要修改 Dapper 的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁人与我共长歌 2025-01-14 10:22:53

就我个人而言,我会建议不要这样做; null 与 NaN 并不完全相同。如果您确实想这样做,则必须查看GetTypeDeserializer。执行此操作的代码是使用 ILGenerator 动态生成的,并且相当复杂。如果您查找一行:

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

如果检测到 DbNull,则代码会分支到该行。它当前所做的只是从堆栈中弹出两个值(值和目标),将它们放在地板上,然后继续。您需要检查 float/double 作为特殊情况,应用转换,然后将 NaN 分配给成员。

不过,我重申我的主张,这根本不是一件有效的事情。一个更简单的选项是:

public double? Value {get;set;}

它需要零更改,并且当前可以工作。如果您确实希望将其视为不可为空的双精度值,也许:

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

现在将默认为 NaN,并在存在值时正确实现。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文