从 ScalarQuery 获取行计数 InvalidCast 异常

发布于 2024-07-09 21:43:20 字数 245 浏览 5 评论 0原文

ScalarQuery<int> query = new ScalarQuery<int>(typeof(Role), 
                         "select count(role.RoleId) from Role as role");
return query.Execute();

它因 invalidcast 异常而失败,但当 count 替换为 max 时成功。

ScalarQuery<int> query = new ScalarQuery<int>(typeof(Role), 
                         "select count(role.RoleId) from Role as role");
return query.Execute();

It fails with the invalidcast exception but succeeds when count is replaced with max.

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

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

发布评论

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

评论(4

夏有森光若流苏 2024-07-16 21:43:21

不完全是问题的答案,但建议:如果您想避免自己发出查询的麻烦,那么只需使用 ActiveRecordMediator.Count() (它有如果您想要条件计数,则采用条件/过滤字符串的重载)并且所有数据库都返回 int

Not exactly the answer to the question, but a recommendation: if you want to avoid the hassle of having to issue a query at all yourself, then just use ActiveRecordMediator<T>.Count() (which has overloads that take criteria / filter strings if you want a conditional count) and all return int against all databases.

新人笑 2024-07-16 21:43:21

根据测试迄今为止给出的答案,以下内容对我有用(包括 where 子句):

// Option 1
int result = ActiveRecordMediator<Post>.Count("BlogId = ?", blogId);

// Option 2
CountQuery query = new CountQuery(typeof(Post), "BlogId = ?", blogId);
int result = ActiveRecordMediator.ExecuteQuery(query);

// Option 3
ScalarQuery<long> query= new ScalarQuery<long>(typeof(Post),
  "SELECT COUNT(*) FROM Post WHERE BlogId = ?", blogId);
long result = query.Execute();

Based on testing the answers given to date, the following worked for me (including a where clause):

// Option 1
int result = ActiveRecordMediator<Post>.Count("BlogId = ?", blogId);

// Option 2
CountQuery query = new CountQuery(typeof(Post), "BlogId = ?", blogId);
int result = ActiveRecordMediator.ExecuteQuery(query);

// Option 3
ScalarQuery<long> query= new ScalarQuery<long>(typeof(Post),
  "SELECT COUNT(*) FROM Post WHERE BlogId = ?", blogId);
long result = query.Execute();
沩ん囻菔务 2024-07-16 21:43:20

编辑:某些数据库会为计数查询返回很长的值。 例如 SQL Server。

ScalarQuery<long> query = new ScalarQuery<long>(typeof(Role), 
                          "select count(r) from Role r");
return query.Execute();

Edit: Some databases will return long for count queries. For example SQL Server.

ScalarQuery<long> query = new ScalarQuery<long>(typeof(Role), 
                          "select count(r) from Role r");
return query.Execute();
烟花肆意 2024-07-16 21:43:20

你使用什么数据库? 可能是 count 不返回 int。

您也可以尝试使用 http://api.castleproject.org/html/T_Castle_ActiveRecord_Queries_CountQuery.htm

What database are you using? Could be that count does not return an int.

Your could also try using http://api.castleproject.org/html/T_Castle_ActiveRecord_Queries_CountQuery.htm

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