Reputation: 103
So I have this Azure function that works, and an Azure SQL DB with some data. But I cannot find a decent example to get data from the DB into the function. Surely, crafting a query string and SQLCommand.BeginExecuteReader/EndExecuteReader is not the preferred way, right? LINQtoSQL perhaps?
Thanks, Bezz
Upvotes: 0
Views: 3613
Reputation: 103
Apparently, it was quite simple. This code did the trick. Although I'm not completely happy with the fact that I'm crafting a query string. For now, it will do.
#r "System.Configuration"
#r "System.Data"
using System.Configuration;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
var str = ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString;
var caterers = new List<string>();
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Caterers";
cmd.Connection = conn;
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
caterers.Add(reader.GetString(1));
}
}
conn.Close();
}
return req.CreateResponse(HttpStatusCode.OK, caterers);
}
Upvotes: 0
Reputation: 35134
You are free to use any .NET Data Access library that's available for other types of applications: ADO.NET, Entity Framework, Dapper etc.
A simple example:
Upvotes: 1