首页 > 代码库 > EF返回DataTable并且返回Json数据

EF返回DataTable并且返回Json数据

public ActionResult GetData()
{
string data = http://www.mamicode.com/Request.Form["Data"] ?? "";
using (var db = new BaseContext())
{
SqlConnection conn = new System.Data.SqlClient.SqlConnection();
//conn.ConnectionString = db.Database.Connection.ConnectionString;

conn.ConnectionString = ConfigurationManager.ConnectionStrings["Service"].ConnectionString;

if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();

cmd.Connection = conn;
cmd.CommandText = "exec pr_database " + data;

SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);

List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

foreach (DataRow Row in table.Rows)
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < Row.ItemArray.Length; i++)
{
row.Add(table.Columns[i].ColumnName, Row[i].ToString());
}
rows.Add(row);

}
var data1 = JsonConvert.SerializeObject(rows);
return Json(data1, JsonRequestBehavior.AllowGet);
//for (int i = 0; i < table.Rows.Count; i++)
//{
// for (int j = 0; j < table.Rows[i].ItemArray.Length; j++)
// {

// }
//}

}

 

EF返回DataTable并且返回Json数据