Introduction
Azure Functions is a solution for easily running small pieces of code, or "functions," in the cloud. You can write just the code you need for the problem at hand, without worrying about a whole application or the infrastructure to run it.
Functions can make development even more productive, and you can use your development languages of choice, such as C#, F#, Node.js, Java, or PHP.
Azure Functions has two kinds of pricing plans,
- Consumption plan
When your function runs, Azure provides all of the necessary computational resources. You don't have to worry about resource management, and you only pay for the time that your code runs.
- App Service plan
Run your functions just like your web, mobile, and API apps. When you are already using App Service for your other applications, you can run your functions on the same plan at no additional cost.
In this post, I will try to make you understand how you can use entity framework with C# code in the Azure function. So, let’s get started.
- Visual Studio creates a new project, then from the cloud section select Azure Functions. Change the Project Name and Location and then click OK.
- In new function dialog select Timer trigger and define the schedule, the schedule is formatted by Cron Expression. To understand that we need to explain the schedule expression.
The cron (chronos) expresses time scheduled jobs as a string format, often segmented to 6 or 7 fields, separated by a space. Let us examine the format with examples.
These fields represent the following,
Seconds | Minutes | Hours | Day of month | Month | Day of week | Year (Optional) |
0-59 | 0-59 | 0-23 | 1-31 | 1-12 or JAN-DEC | 0-6 or MON-SUN | 1970-2099 |
Let’s look at some basic examples of expressions,
Expression | Behavior |
0 * * * * * | Trigger at Zero second on any minute, any hour, any day. Effectively triggering once every 60 seconds |
0 0 * * * * | Trigger at Zero second and Zero minute on any hour, any day. Effectively triggering once every 60 minutes. Because the occurrence of 0 second and 0 minute happens once an hour |
0 15 * * * * | Trigger at Zero second and 15th minute, any hour, any day. Effectively triggering once every 60 minutes at the 15th minute mark |
30 30 1 * * * | Trigger at 30th second and 30th minute and 1st hour, any day. Effectively triggering once, a day at 01:30:30 AM |
0 0 0 * MON, TUE, WED, FRI | Trigger at Zero second and Zero minute and Zero hour, any day of the Month and on MON, TUE, WED, FRI. Effectively triggering at midnight on the days of Monday, Tuesday, Wednesday and Friday |
Let us explore a more useful feature of the expression:
Expression | Behavior |
*/1 * * * * * | Trigger at any second. Effectively triggering every second |
*/30 * * * * * | Trigger at any 30 second interval. Effectively triggering every 30 seconds |
0 */5 * * * * | Trigger at Zero second and any 5th minute. Effectively triggering at zero second every 5 minutes |
0 30 */6 * * * | Trigger at Zero second and 30th minute at any six hour interval. Effectively triggering every 6 hours at 30 min and zero second. |
This site helps us to generate cron expression with an easy to use online interface. Convert a cron expression into a readable text that clearly explains when it will execute, and visualize the next execution dates of your cron.
- Next, we need the entity framework package from NuGet Packages.
- Create Data Context Class, in this post I will create EmployeeDataContext that inherits from DbContext. I defined the connection string name “mycs” and create Employee entity class.
- public class EmployeeDataContext: DbContext {
- public EmployeeDataContext(): base("name=mycs") {}
- public DbSet < Employee > Employees {
- get;
- set;
- }
- }
- Create Employee entity class
- public class Employee {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public DateTime JoinDate {
- get;
- set;
- }
- public decimal VacationBalance {
- get;
- set;
- }
- public DateTime UpdateDate {
- get;
- set;
- }
- public decimal Salary {
- get;
- set;
- }
- }
- Now, I need to defined the connection string value to do that open local.settings.json file then add the following,
- "connectionStrings": {
- "mycs": {
- "ConnectionString": "Data Source=.;Initial Catalog=EmployeeDb;Integrated Security=True;MultipleActiveResultSets=True",
- "ProviderName": "System.Data.SqlClient"
- }
- }
- The complete file will be like this,
- {
- "IsEncrypted": false,
- "Values": {
- "AzureWebJobsStorage": "UseDevelopmentStorage=true",
- "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
- },
- "connectionStrings": {
- "mycs": {
- "ConnectionString": "Data Source=.;Initial Catalog=EmployeeDb;Integrated Security=True;MultipleActiveResultSets=True",
- "ProviderName": "System.Data.SqlClient"
- }
- }
- }
- Rename the Function1.cs file to suitable name, and then change the code to become as the below code,
- [FunctionName("VacationBalance")]
- public static void Run([TimerTrigger("0/30 * * * * *")] TimerInfo myTimer, TraceWriter log) {
- EmployeeDataContext employeeDataContext = new EmployeeDataContext();
- var lstEmployees = employeeDataContext.Employees;
- foreach(var item in lstEmployees) {
- item.VacationBalance += 1;
- }
- employeeDataContext.SaveChanges();
-
- }
- For testing purposes, I set the schedule every 30 seconds. [TimerTrigger("0/30 * * * * *")]
- To test before deployment to Azure try to run the application by pressing F5.
- Now, we are ready to deploy this function to Azure, to do that right click on your project and select Publish. In publishing dialog select “Create New” option. Then click the publish button.
- Fill all fields then click on create.
- In publishing dialog click publish to publish your function.
- After completing publish go to https://portal.azure.com/ and open functions app from the left menu.
- Click on function app name from dashboard then click on application settings link.
- To get the connection string, click on SQL Databases in the left menu and then select the database from Connection strings to click on Show database connection strings, copy it, and don’t forget to change {user id} and {password}.
- Back to function application settings, form connection strings -- add the connection string with the same name. Then click the save button.
- Congratulations, your Azure function is ready.