2012-03-03 117 views
1

我的代码:无法隐式转换类型 'System.Collections.Generic.IEnumerable <dynamic>' 到 '廉政'

int key = 0; 
      //get primary key of inserted row 
      key = db.Query("SELECT max(event_id) FROM event where title=" + cevent.title + "AND description=" + cevent.description + "AND event_start=" + cevent.start + "AND event_end=" + cevent.end); 

错误消息:

无法隐式转换类型 “System.Collections中。 Generic.IEnumerable'到'int'

我正在使用C#,WebMatrix和SQL Server。 WebMatrix中。如果我尝试运行的ExecuteScalar代替查询,我得到

“WebMatrix.Data.Database”不包含一个定义 “的ExecuteScalar”

有谁知道我能做些什么来解决我的代码?

+0

也许'db.Query'返回一个IEnumerable而不是int ??错误信息很清楚。 – vulkanino 2012-03-03 17:58:19

回答

1

这听起来像你想要Database.QueryValue来代替。

// No need to declare it beforehand... 
int key = (int) db.QueryValue(...); 

而且在你前面的问题,你绝对应该被嵌入SQL中的查询参数值。

Database.QueryValue被记录为:

执行返回单个标量值作为结果的SQL查询。

......这听起来恰到好处。这是值得浏览文档 - 他们不是很详细,但它至少会告诉你什么是可用的。

+0

不用担心,我的工作将会得到解决!非常感谢回复: – 2012-03-03 17:59:25

0

你的key是整数,你不能投一个整数System.Collections.Generic.IEnumerable,作为消息报答。

如果肯定有结果只有一个,写的是这样的:

key = (int)db.Query("SELECT max(event_id) FROM event where title=" + 
          cevent.title + "AND description=" + 
          cevent.description + "AND event_start=" + 
          cevent.start + "AND event_end=" + cevent.end). 
          FirstOrDefault(); 

应该足够给你。

+0

如果您确定只有一个结果,那么'SingleOrDefault()'比'FirstOrDefault()'更合适。 – BACON 2012-03-03 20:13:08

相关问题