2

我在我的项目中使用,这是一个漂亮的工具,用于将SQL query结果存储到 a 中List,并且效果很好。

我写了SQL query一个从数据库中获取记录并将结果存储在一个变量中,我尝试使用dapper但遇到了一个错误。我已经粘贴了相应的代码。

例外:无法将“System.Collections.Generic.List`1[Dapper.SqlMapper+DapperRow]”类型的对象转换为“System.IConvertible”类型。

try
{
  using(var connection = ...)
  {
   connection.Open();
   const string masterSelectQuery = "SELECT Id as [fileId], FileName as [fileName], Frequency as [frequency], Scheduled_Time as scheduledTime FROM MASTER_TABLE";
   masterTableList = connection.Query<MasterTableAttributes>(masterSelectQuery).ToList();//Working fine

   const string lastProcessedTimeQuery = "SELECT TOP 1 file_transfered_time as [lastProcessedTime] FROM PROCESS_LOGS ORDER BY file_transfered_time DESC";
   DateTime lastProcessedTime = Convert.ToDateTime(connection.Query(lastProcessedTimeQuery)); //Here it fails
  }    
}

为了克服这个错误,我使用SQLCommand如下

using (command = new SqlCommand(lastProcessedTimeQuery, connection))
{
  DateTime lastProcessedTime = (DateTime)command.ExecuteScalar();//working fine  
}

我在使用 dapper 时犯了一个错误,有人可以指导我吗?

提前致谢。

4

1 回答 1

4

connection.Query(lastProcessedTimeQuery)返回一系列行,每一行都是单独dynamic。假设file_transfered_time是 a datetime,你有两个选择:

DateTime lastProcessedTime = connection.Query<DateTime>(
                 lastProcessedTimeQuery).Single();

或者,展示非泛型如何Querydynamic一行一起工作:

DateTime lastProcessedTime = connection.Query(
                 lastProcessedTimeQuery).Single().lastProcessedTime;

如果您的PROCESS_LOGS桌子可能是空的,您可能更喜欢SingleOrDefault

DateTime? lastProcessedTime = connection.Query<DateTime?>(
                 lastProcessedTimeQuery).SingleOrDefault();

或者:

var row = connection.Query(lastProcessedTimeQuery).SingleOrDefault();
DateTime? lastProcessedTime = null;
if(row != null) lastProcessedTime = row.lastProcessedTime;
于 2013-06-13T12:54:31.067 回答