为什么 PetaPoco 从 db.Insert ID 字段返回 7 作为十进制
当执行插入时,变量 id 作为对象返回。然而,在我的数据库中它是一个 int,在我的 POCO 中它是一个 int,但是当调用 ExecuteScalar 返回 @@IDENTITY 的方法时,它返回数字 7 作为对象,但调试器认为它是十进制。
因此,当我执行 int newID = (int)db.Insert(...)
时,它会抛出
InvalidCastException
Is this a Framework bug or a PetaPoco bug?
When doing a Insert the variable id is returned as an object. However in my database it is an int and in my POCO it is an int however when the method call to ExecuteScalar to return @@IDENTITY is called it returns the number 7 as an object but the debugger thinks its a decimal.
Therefore when I do int newID = (int)db.Insert(...)
it throws a
InvalidCastException
Is this a framework bug or a PetaPoco bug?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
还要记住,如果您已经设置了班级并像这样插入。
user.Id
现在将从 0 更改为新创建的身份值Also remember that if you have set your class up and you insert like so.
user.Id
will now change from 0 to the newly created identity value这将取决于您要连接到的 RDBMS(您没有说明)。
下面是来自 PetaPoco 的相关代码,用于检索最后一个 id 并返回它:
It's going to depend on what RDBMS you are connecting to, which you didn't state.
Here's the relevant code from PetaPoco that retrieves the last id and returns it:
另外两分钱。正如已经回答的那样,PetaPoco 返回 SQL Server 插入的小数。问题作者正在尝试转换为引发 InvalidCastException 的 int 。但是,类型转换确实有效。因此,不要这样做:
这样做:
Another two cents. As already answered PetaPoco returns a decimal for SQL Server Inserts. The question author is attemping to cast to an int which throws an InvalidCastException. However, a Type Conversion does work. So instead of this:
do this:
这是一个猜测,但值得一试。在 PetePoco.cs 中尝试将 : 更改
为
It's a guess but worth a go. In PetePoco.cs try changing :
to