无法将类型'System.Data.DataSet'隐式转换为'System.Collections.Generic.List <calendarevent>''</calendarevent>

时间:2013-11-27 10:31:38

标签: html asp.net sql-server

我是应用程序块的新手。

我正在尝试从数据库中获取数据。以下是代码捕捉。

JsonResponse.ashx:

public void ProcessRequest(HttpContext context)
{
    HttpContext _context = HttpContext.Current;

    context.Response.ContentType = "application/json";
    int user_id = Convert.ToInt32(HttpContext.Current.Session["userid"]);
    DateTime start = new DateTime(1970, 1, 1);
    DateTime end = new DateTime(1970, 1, 1);

    start = start.AddSeconds(double.Parse(context.Request.QueryString["start"]));
    end = end.AddSeconds(double.Parse(context.Request.QueryString["end"]));       
    String result = String.Empty;

    result += "[";

    List<int> idList = new List<int>();
    foreach (CalendarEvent cevent in EventDAO.getEvents(start, end, user_id))
    {
        result += convertCalendarEventIntoString(cevent);
        idList.Add(cevent.id);
    }

    if (result.EndsWith(","))
    {
        result = result.Substring(0, result.Length - 1);
    }

    result += "]";
    //store list of event ids in Session, so that it can be accessed in web methods
    context.Session["idList"] = idList;

    context.Response.Write(result);
}

private String convertCalendarEventIntoString(CalendarEvent cevent)
{
    String allDay = "true";
    if (ConvertToTimestamp(cevent.start).ToString().Equals(ConvertToTimestamp(cevent.end).ToString()))
    {

        if (cevent.start.Hour == 0 && cevent.start.Minute == 0 && cevent.start.Second == 0)
        {
            allDay = "true";
        }
        else
        {
            allDay = "false";
        }
    }
    else
    {
        if (cevent.start.Hour == 0 && cevent.start.Minute == 0 && cevent.start.Second == 0
            && cevent.end.Hour == 0 && cevent.end.Minute == 0 && cevent.end.Second == 0)
        {
            allDay = "true";
        }
        else
        {
            allDay = "false";
        }
    }
    return    "{" +
              "id: '" + cevent.id + "'," +
              "title: '" + HttpContext.Current.Server.HtmlEncode(cevent.title) + "'," +
              "start:  " + ConvertToTimestamp(cevent.start).ToString() + "," +
              "end: " + ConvertToTimestamp(cevent.end).ToString() + "," +
              "allDay:" + allDay + "," +
                "user_id:" + cevent.user_id + "," +
              "description: '" + HttpContext.Current.Server.HtmlEncode(cevent.description) + "'" +

              "},";
}

DA:

public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{

    List<CalendarEvent> events = new List<CalendarEvent>();

    SqlParameter[] sqlParam = new SqlParameter[3];
    sqlParam[0] = new SqlParameter("@start", start);
    sqlParam[1] = new SqlParameter("@end", end);
    sqlParam[2] = new SqlParameter("@user_id", user_id);
    return SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
}

提供SQLHelper:

public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
    //create a command and prepare it for execution
    SqlCommand cmd = new SqlCommand();
    cmd.CommandTimeout = 120;
    PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

    //create the DataAdapter & DataSet
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();

    //fill the DataSet using default values for DataTable names, etc.
    da.Fill(ds);

    // detach the SqlParameters from the command object, so they can be used again.         
    cmd.Parameters.Clear();

    //return the dataset
    return ds;                      
}

我收到错误:

  

无法将类型'System.Data.DataSet'隐式转换为'System.Collections.Generic.List'。

我无法理解这是什么问题。

3 个答案:

答案 0 :(得分:0)

getEvents方法中,您需要遍历数据集中的记录并填写您将在此方法中返回的列表。

var dataset = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);

foreach (var row in ds.Tables["FooTable"].Rows)
{
     events.Add(new CalendarEvent(...));
}

return events;

答案 1 :(得分:0)

那是因为您尝试将数据集作为List返回,而不是。 您需要将数据集转换为列表。一种可能的解决方案是将getEvents方法更改为类似的方法 - &gt;

public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{

    List<CalendarEvent> events = new List<CalendarEvent>();

    SqlParameter[] sqlParam = new SqlParameter[3];
    sqlParam[0] = new SqlParameter("@start", start);
    sqlParam[1] = new SqlParameter("@end", end);
    sqlParam[2] = new SqlParameter("@user_id", user_id);
    var ds = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
    return ds.Tables[0].AsEnumerable().Select(datarow => new CalendarEvent{ Title = datarow.Field<string>("Title), /*the rest of your params*/}).ToList();
}

答案 2 :(得分:0)

你的问题就是这段代码:

public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
    List<CalendarEvent> events = new List<CalendarEvent>();
    SqlParameter[] sqlParam = new SqlParameter[3];
    sqlParam[0] = new SqlParameter("@start", start);
    sqlParam[1] = new SqlParameter("@end", end);
    sqlParam[2] = new SqlParameter("@user_id", user_id);
    return SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
}

您已将此方法的类型定义为List<CalenderEvent>,但您返回DataSet。 我不知道您的数据集中包含哪些数据表,但我认为有一个表示您的calenderevents。

这意味着您需要从数据集中提取所需的数据并从中生成列表。假设数据集中有一个表,您的新方法将如下所示:

public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
    List<CalendarEvent> events = new List<CalendarEvent>();
    SqlParameter[] sqlParam = new SqlParameter[3];
    sqlParam[0] = new SqlParameter("@start", start);
    sqlParam[1] = new SqlParameter("@end", end);
    sqlParam[2] = new SqlParameter("@user_id", user_id);


    var data = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
    events = ds.Tables[0].AsEnumerable().Select(r => new CalenderEvent 
                                         {
                                           //using dummy properties because I dont know 
                                           //your class
                                           Property1 = r.Field<string>("Column1"),
                                           Property2 = r.Field<string>("column2"),
                                           //...
                                         }).ToList();
    return events;
}