0

我是 C# 的新手。如何在 Razor 视图中显示 SQL?

// GET: /ReportData
public ActionResult Index()
{
    using (SqlConnection connection = new SqlConnection(@"Data Source=xxx.xxx.xxx.xxx;Initial Catalog=xxxxxx;Persist Security Info=True;User ID=xxxxx;Password=xxxxx"))
    {
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = @"select * from ProjectManagement as p 
            join Implementation as i on p.JobNumber = i.JobNumber 
            join Divisions as d on i.Division = d.Division 
            where p.ProjectStatus = 'Active'"

            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    // process result
                    reader.GetValue(0);
                    reader.GetValue(1);
                    reader.GetValue(2);
                    reader.GetValue(3);
                    reader.GetValue(4);
                    reader.GetValue(5);
                }

            }
        }
    }         

    return View();
}    

我知道这取决于读者对象,但之后我不知道如何继续。只需要大意...

4

1 回答 1

0

您确实需要研究实体框架并开始建模。这个问题需要很多东西才能回答。

Microsoft 的 EF(实体框架)http://msdn.microsoft.com/en-us/data/ef.aspx 或者当然使用 stackoverflow 并使用剃刀寻找实体框架和视图模型。

上面的答案将假设您正在使用它,并且不适用于您正在做的循环数据库的旧方法。这确实不是一个很好的答案,但是您需要对实体框架或另一个 ORM(对象关系映射器)进行一些研究,这应该可以帮助您前进。

// GET: /ReportData
public ActionResult Index()
{
    List<DataHolder> data = new List<DataHolder>();
    using (SqlConnection connection = new SqlConnection(@"Data Source=xxx.xxx.xxx.xxx;Initial Catalog=xxxxxx;Persist Security Info=True;User ID=xxxxx;Password=xxxxx"))
    {

        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = @"select * from ProjectManagement as p 
            join Implementation as i on p.JobNumber = i.JobNumber 
            join Divisions as d on i.Division = d.Division 
            where p.ProjectStatus = 'Active'"

            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {                  
                while (reader.Read())
                {
                   data.Add( new DataHolder {
                      Item1 = reader.GetValue(0),
                      Item2 = reader.GetValue(1)
                   });
                    // process result
                    //reader.GetValue(0);
                    //reader.GetValue(1);
                    //reader.GetValue(2);
                    //reader.GetValue(3);
                    //reader.GetValue(4);
                    //reader.GetValue(5);
                }

            }
        }
    }         

    return View(data);
}


public class DataHolder {
  public string Item1 { get; set; }
  public string Item2 { get; set; }
}

然后在view.cshtml

@model List<DataHolder>

@foreach(var a in Model) {
  <p>@a.Item1 @a.Item2</p>
}
于 2013-11-05T04:29:27.467 回答