c# - 查询数据库出错

标签 c# sql

我的代码:

var db = Database.Open("dbase");
var result = db.Query("SELECT event_id, description, title, event_start, event_end 
                       FROM event 
                       WHERE event_start >= "+ start + " AND event_end <= "+ @end);

foreach(var record in result)
{
   CalendarEvent cevent = new CalendarEvent();
   cevent.id = result.event_id; //error is thrown here
}

错误信息:

CS1061: 'System.Collections.Generic.IEnumerable' does not contain a definition for 'event_id' and no extension method 'event_id' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)

在我的代码中我有:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using WebMatrix.Data;

这是什么原因造成的?

最佳答案

首先,您的意思可能是 record.event_id而不是 result.event_id .如果您更改 result,您的代码会更清晰至 results ,鉴于它是结果的序列

但是,这只会将问题转移到一个阶段。 Database.Query 返回 IEnumerable<object> , 所以 record 的类型将是 object ... 和 object没有名为 event_id 的成员要么。

Database.Query 的文档非常模糊-它可能会返回动态对象。试试这个:

foreach (dynamic record in result)
{
        CalendarEvent cevent = new CalendarEvent();
        cevent.id = record.event_id;
}

编辑:如果record.event_id即使没有转换为 dynamic 也能正常工作, 那么有效结果类型可能是IEnumerable<dynamic> MSDN 并没有提供太大帮助。

但是,您的代码中仍然存在问题:像这样将参数值直接包含在 SQL 中是个坏主意:

  • 就代码清洁度而言,混合代码和数据不是一个好主意
  • 您需要确保日期、数字等的格式正确
  • 它使您容易受到 SQL 注入(inject)攻击

相反,您应该像这样使用参数化查询:

var result = db.Query(
     "SELECT event_id, description, title, event_start, event_end FROM event " +
     "where event_start >= ? AND event_end <= ?",
     start, end);        

关于c# - 查询数据库出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548120/

相关文章:

c# - 单击按钮停止刷新页面

sql - SQL Server 2008 R2 中的类型表无法工作?

java - 插入数据时JDBC连接错误

mysql - mysql查询日期间隔的替代方案

sql - 为 SqlServer 查找表使用 tinyint 而不是 int 值得麻烦吗?

c# - c# 中带有列表的动态类型

c# - 写入文本文件 C#

c# - WPF:如何将 GeneralTransform 应用于几何数据并返回新几何?

sql - 如何在SQL中的两列上交叉分组?

c# - 使用 DI 访问 Startup.cs 中的 NPGSQL