In most of my projects with an Azure Function App I used ADO.NET for the database connection. Last I found an article that made a connection by using the Entity Framework. Entity Framework is known for its capability of object based development, maintainability and for reducing development time and cost. Let’s try this in a demo project before using it in a real project.

Creating the Azure objects

For this demo, we will need an Azure SQL database and an Azure Function App.

  1. Open the Azure portal and create a SQL server and SQL database
  2. Open the created SQL Server and go to “Networking” and “Add your client IPv4 address”
  3. Also “Allow Azure services and resources to access this server”
  4. Go to the created database and copy the connectionstring and store it in notepad. We will need this later.
  5. Create a table by opening the “Query editor” in the created database and execute the code below. It is also possible to open the database via SQL Server Management studio and execute the query
    Create table dbo.telemetry (
    ID int identity(1,1) PRIMARY KEY,
    DeviceId nvarchar(150) NOT NULL,
    DatetimeUTC datetime NOT NULL,
    Temperature decimal(18,6) NULL
    )
  6. Next, create an Azure Function App, with the settings:
    • Runtime stack: .NETVersion: 3.1
    • Operating system: Windows
  7. When the Function App is created, add a “Application setting” in the “Configuration” menu item
    • Name: SqlConnectionString
    • Value: <The connectionstring from de database>

Creating an Azure Functions project

  1. Open Visual Studio and create a new project: Azure Functions

  2. Next give your project a name and click on create
  3. To help you get started select a type of application, in this case I used the Timer trigger. In the right site of the screen set a schedule for the timer (NCRONTAB expression). We will use a time trigger for every 5 minutes.
  4. Your project will be created and it will result in a basic Azure Function with no functionality based on a timer trigger.
  5. Add the following NuGet references to the project (use the version specified, higher versions won’t work):
    • Microsoft.EntityFrameworkCore 3.1.27
    • Microsoft.EntityFrameworkCore.SqlServer 3.1.27

Let’s start developing

Add a Telemetry.cs class:

    [Table("Telemetry")]
    public class Telemetry
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public string DeviceId { get; set; }
        public DateTime DatetimeUTC { get; set; }
        public double Temperature { get; set; }
    }

I added the TableAttribute to map this class to the table and the KeyAttribute to ID because this is our primary key. Last but not least I also added a DatabaseGeneratedAttribute to ID because we created the table first with an identity column.

Next create a MyDbContext.cs class

 public class MyDbContext : DbContext
    {
        protected readonly string _connectionString;
        public MyDbContext(string connectionString) : base()
        {
            _connectionString = connectionString;
        }
      
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            // connect to sql server with connection string
            options.UseSqlServer(_connectionString);          
        }
        public DbSet<Telemetry> TelemetrySet { get; set; }
    }

All the preparations are done, so now we can start with the actual function. I renamed the function from Function1.cs to FunctionAppDemo.cs. In the function I added the code which creates a Telemetry object and saves it to the database. The SqlConnectionString will be fetched from the Function App Application settings.

public class FunctionAppDemo
    {
        private static string SqlConnectionString = Environment.GetEnvironmentVariable("SqlConnectionString");
        [FunctionName("FunctionAppDemo")]
        public void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            using (var MyDbContext = new MyDbContext(SqlConnectionString))
            {
                Random random = new Random();
                Telemetry t = new Telemetry { DeviceId = "Azure Demo", DatetimeUTC = DateTime.UtcNow, Temperature = random.NextDouble() };
                MyDbContext.TelemetrySet.Add(t);
                MyDbContext.SaveChanges();
            }
            log.LogInformation($"{DateTime.Now} - Telemetry saved to database");
        }
    }

Publish the function to Azure

  1. To publish the function to Azure right-click on your project and select publish.
  2. We are publishing to Azure Function App (Windows)
    1. Target
    2. Specific Target
  3. Next you see all the Function Apps in your subscription. Select the Function App you generated in the first step and click on finish.
  4. The publish window will now open and we can publish the app by clicking the button in the top right corner.
  5. If everything succeeds you will see something like this in the output window:

Test the Function App

  1. Open the Azure portal again and open the Function App
  2. In the menu select “Functions” and click on your function
  3. Then go to “Code + Test” and select “Test/Run”
  4. Now click Run twice, the first time a new window will open with the logging of the Function App, the second time the function is executed.
  5. Finally, we should check the database, if there are records added:

Conclusion

Actually, it was pretty easy to switch to Entity Framework for an Azure Function App. The hardest part was finding the right version of the Entity Framework that worked in the Azure Function App.

The fact that we can use object classes and write them directly to the database will reduce development time and costs. Therefore using Entity Framework is a good alternative to use in a real project.