将SQL代码转换为Razor格式

时间:2012-03-03 00:02:59

标签: c# sql sql-server razor

我正在尝试将一些旧的C#代码转换为WebMatrix访问数据库的方式,但我正在努力。有人可以帮帮我吗?

    private static string connectionString = "Data Source=ASHIT\\SQLEXPRESS;Initial Catalog=amit;Integrated Security=True";

    public static List<Item> method(DateTime start, DateTime end)
    {

        List<Item> events = new List<Item>();
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("SELECT event_id, description, title, event_start, event_end FROM event where event_start>=@start AND event_end<=@end", con);
        cmd.Parameters.AddWithValue("@start", start);
        cmd.Parameters.AddWithValue("@end", end);

        using (con)
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                //perform functions
            }
        }
        return events;
    }

到目前为止,我有这么多,而且我无法完成“使用”行 - 我应该从哪里开始?

public static List<Item> method(DateTime start, DateTime end)
    {

        List<Item> events = new List<Item>();
        var db = Database.Open("plan");
        var result = db.Query("SELECT event_id, description, title, event_start, event_end FROM event where event_start>= "+ start + " AND event_end<= "+ @end);
    //not sure what to do from here
        using (con)
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                //perform functions
            }
        }
        return events;
    }

1 个答案:

答案 0 :(得分:1)

我从未使用过WebMatrix的数据库帮助程序,但根据文档,您应该可以执行以下操作:

foreach(var record in result)
{
    // Perform functions
}

再次查看文档,看起来db.Query将返回IEnumerable<Object>,因此除非您将其更改为(仅限C#4),否则上述代码将无效:

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

根据示例here,可能没有必要这样做。