3 Simple ways to retrieve generic SQL data with C# / WebAPI controller (using DataRow)
Full Code in the end! :)
Assuming you have some connection string:
private static string ConnectionString = ConfigurationManager.AppSettings["myConnStrApp"];
- return (convert to) Json String
- build json object
But what if we have multiple tables? What if we just want to test things? What if we expect Changes? Or maybe I just dont wanna cuz its of no use?
GENERICS OPTIONS (after code above)
Return (convert to) JSON String
pro: most simple, least amount of code, can be tested with xml view on browser
con: its a string and not an object, needs to be parsed at client (JSON.parse)
Change the method to return string and add this line:
return JsonConvert.SerializeObject(ds.Tables[0]);
Build JSON Object
pro: simple generic json object in c#
con: 6 rows instead of 1 lol, no xml testing
Change the method to return objectand add this line:
string[] cols = ds.Tables[0].Columns.Cast<DataColumn>().Select(d=> d.ColumnName).ToArray();
var rows = ds.Tables[0].Rows;
return ds.Tables[0].Rows.Cast<DataRow>().Select(r => {
var jo = new JObject();
foreach (string c in cols) { jo.Add(c, JToken.FromObject(r[c])); }
return jo;
});
The "Select" are just fancy way to do "foreach" with LINQ.
xml testing by browse:
here are the source codes:
- the code in the example (DB_example.cs)
- full power generic DAL with alot of stuff, Reflection and CRUD and more (DAL.cs).
Comments
Post a Comment