不通过model获取数据库数据

[HttpGet]
    [ActionName("getViewData")]
    public HttpResponseMessage GetView(string view_name)
    {

        HttpResponseMessage response;
        try
        {
            string sql = " IF EXISTS ( SELECT * FROM sys.views WHERE object_id = OBJECT_ID (N'" + view_name + "', N'V'))   SELECT * FROM " + view_name + "";
            SqlConnection sqlConn = new SqlConnection();
            sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            SqlCommand sqlCmd = new SqlCommand(sql, sqlConn);
            SqlDataAdapter sqlAdp = new SqlDataAdapter(sqlCmd);
            DataSet ds = new DataSet();
            sqlAdp.Fill(ds);
            if ( ds.Tables.Count == 0)
            {
                var resp = new
                {
                    response = 1,
                    error = "这个视图没找到或者不存在"
                };
                response = Request.CreateResponse(HttpStatusCode.NotFound, resp);
            }
            else
            {
                DataTable dt = ds.Tables[0];
                var dept = dt.AsEnumerable()
                    .Select(r => r.Table.Columns.Cast()
                            .Select(c => new KeyValuePair(c.ColumnName, r[c.Ordinal])
                           ).ToDictionary(z => z.Key, z => z.Value)
                    ).ToList();


                var resp = new
                {
                    response = 1,
                    error = "",
                    result = dept
                };

                response = Request.CreateResponse(HttpStatusCode.OK, resp);

            }
        }
        catch (Exception ex)
        {
            var resp = new
            {
                response = 0,
                error = ex.Message

            };

            response = Request.CreateResponse(HttpStatusCode.OK, resp);
        }

        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            MaxAge = TimeSpan.FromMinutes(1)
        };
        response.Headers.Add("Access-Control-Allow-Origin", "*");
        return response;
    }

你可能感兴趣的:(不通过model获取数据库数据)