Azure Function With Entity Framework

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.

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.

  1. Visual Studio creates a new project, then from the cloud section select Azure Functions. Change the Project Name and Location and then click OK.

    Azure
  1. 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.

    Azure

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,

SecondsMinutesHoursDay of monthMonthDay of weekYear (Optional)
0-590-590-231-311-12 or JAN-DEC0-6 or MON-SUN1970-2099

Let’s look at some basic examples of expressions,

ExpressionBehavior
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, FRITrigger 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:

ExpressionBehavior
*/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.

  1. Next, we need the entity framework package from NuGet Packages.

    Azure
  1. 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.
    1. public class EmployeeDataContext: DbContext {  
    2.     public EmployeeDataContext(): base("name=mycs") {}  
    3.     public DbSet < Employee > Employees {  
    4.         get;  
    5.         set;  
    6.     }  
    7. }  
  1. Create Employee entity class
    1. public class Employee {  
    2.     public int Id {  
    3.         get;  
    4.         set;  
    5.     }  
    6.     public string Name {  
    7.         get;  
    8.         set;  
    9.     }  
    10.     public DateTime JoinDate {  
    11.         get;  
    12.         set;  
    13.     }  
    14.     public decimal VacationBalance {  
    15.         get;  
    16.         set;  
    17.     }  
    18.     public DateTime UpdateDate {  
    19.         get;  
    20.         set;  
    21.     }  
    22.     public decimal Salary {  
    23.         get;  
    24.         set;  
    25.     }  
    26. }  
  1. Now, I need to defined the connection string value to do that open local.settings.json file then add the following,
    1. "connectionStrings": {  
    2.     "mycs": {  
    3.         "ConnectionString""Data Source=.;Initial Catalog=EmployeeDb;Integrated Security=True;MultipleActiveResultSets=True",  
    4.         "ProviderName""System.Data.SqlClient"  
    5.     }  
    6. }  
  1. The complete file will be like this,
    1. {  
    2.     "IsEncrypted"false,  
    3.     "Values": {  
    4.         "AzureWebJobsStorage""UseDevelopmentStorage=true",  
    5.         "AzureWebJobsDashboard""UseDevelopmentStorage=true"  
    6.     },  
    7.     "connectionStrings": {  
    8.         "mycs": {  
    9.             "ConnectionString""Data Source=.;Initial Catalog=EmployeeDb;Integrated Security=True;MultipleActiveResultSets=True",  
    10.             "ProviderName""System.Data.SqlClient"  
    11.         }  
    12.     }  
    13. }  
  1. Rename the Function1.cs file to suitable name, and then change the code to become as the below code,
    1. [FunctionName("VacationBalance")]  
    2. public static void Run([TimerTrigger("0/30 * * * * *")] TimerInfo myTimer, TraceWriter log) {  
    3.     EmployeeDataContext employeeDataContext = new EmployeeDataContext();  
    4.     var lstEmployees = employeeDataContext.Employees;  
    5.     foreach(var item in lstEmployees) {  
    6.         item.VacationBalance += 1;  
    7.     }  
    8.     employeeDataContext.SaveChanges();  
    9.     // log.Info($"C# Timer trigger function executed at: {DateTime.Now}");  
    10. }  
  1. For testing purposes, I set the schedule every 30 seconds. [TimerTrigger("0/30 * * * * *")]

  2. To test before deployment to Azure try to run the application by pressing F5.

    Azure
  1. 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.

    Azure

  2. Fill all fields then click on create.

    Azure

  3. In publishing dialog click publish to publish your function.
    Azure
  1. After completing publish go to https://portal.azure.com/ and open functions app from the left menu.

    Azure
  1. Click on function app name from dashboard then click on application settings link.

    Azure
  1. 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}.
  1. Back to function application settings, form connection strings --  add the connection string with the same name. Then click the save button.
    Azure
  1. Congratulations, your Azure function is ready.