How to connect to a DB ?
Azure Cosmos DB
To use Azure Cosmos DB in serverless mode, choose Serverless as the Capacity mode when creating your account.
1.Register binding extensions
dotnet add package Microsoft.Azure.WebJobs.Extensions.CosmosDB --version 3.0.10
2.Add an output binding
[CosmosDB(databaseName: "my-database", collectionName: "my-container", ConnectionStringSetting = "CosmosDbConnectionString"
)]IAsyncCollector<dynamic> documentsOut,
3.Add code that uses the output binding
[FunctionName("HttpExample")]
public static async Task<IActionResult> Run(HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
[CosmosDB(
databaseName: "my-database",
collectionName: "my-container",
ConnectionStringSetting = "CosmosDbConnectionString")]IAsyncCollector<dynamic> documentsOut,ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
if (!string.IsNullOrEmpty(name))
{
// Add a JSON document to the output container.
await documentsOut.AddAsync(new
{
// create a random ID
id = System.Guid.NewGuid().ToString(),
name = name
});
}
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
}
Azure SQL
Verify that your Azure Function will be able to access the Azure SQL Database by checking the server's firewall settings : Network Access Controls - Azure SQL Database & Azure Synapse Analytics | Microsoft Learn. Navigate to the server blade on the Azure portal, and under Security, select Networking. The exception for Allow Azure services and resources to access this server should be checked.
1.Register binding extensions
2.Add an output binding
Add the following ToDoItem
class, which defines the object that is written to the database.
The toDoItems parameter is an IAsyncCollector<ToDoItem> type, which represents a collection of ToDo items that are written to your Azure SQL Database when the function completes.
3.Add code that uses the output binding