Use Entity Framework in .NET 5 Azure Functions

Raymond Raymond visibility 2,851 event 2021-08-24 access_time 3 years ago language English

Entity Framework can be used in .NET 5 Azure Functions for many different use cases, for example, using it to connect to a database like Azure SQL Database, MySQL or any other accessible and supported databases. 


The code snippet used in this article builds on top of the following ones:

In this article, I am going to show you how to create a DbContext object and then use it in Azure Functions to write data and read data from a in-memory database.

Add package references

Add the following package references in the sample project:

    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage" Version="4.0.4" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.0.3" OutputItemType="Analyzer" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.9" />

Create a sample DbContext and model

Add a model class named ApplicationUser into the project using the following code snippet:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AzureFunctionExample
    public class ApplicationUser
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

Then add a DbContext named ApplicationDbContext:

using Microsoft.EntityFrameworkCore;

namespace AzureFunctionExample
    public class ApplicationDbContext : DbContext
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)

        public DbSet<ApplicationUser> ApplicationUsers { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)

Register the DbContext

Register ApplicationDbContext in Program.cs.

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AzureFunctionExample
    public class Program
        public static void Main()
            var host = new HostBuilder()
                .ConfigureAppConfiguration(config =>
                    config.AddJsonFile("appsettings.json", false, false).AddEnvironmentVariables().Build();
                .ConfigureServices(services =>
                    services.AddOptions<AppConfig>().Configure<IConfiguration>((settings, configuration) => configuration.GetSection("AppConfig").Bind(settings));
                    services.AddDbContext<ApplicationDbContext>(options =>


Use ApplicationDbContext

Update Function1 to use ApplicationDbContext. The following highlighted lines are added to consume ApplicationDbContext. The first section creates a new entity while the second section reads all the available entities in Users table.

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace AzureFunctionExample
    public class Function1
        private readonly IOptions<AppConfig> appConfig;
        private readonly ApplicationDbContext dbContext;

        public Function1(IOptions<AppConfig> appConfig, ApplicationDbContext dbContext)
            this.appConfig = appConfig;
            this.dbContext = dbContext;

        public void Run([BlobTrigger("blob-triggers/{name}", Connection = "AzureWebJobsStorage")] string myBlob, string name,
            FunctionContext context)
            var logger = context.GetLogger("Function1");
            logger.LogInformation($"C# Blob trigger function Processed blob\n Name: {name} \n Data: {myBlob}");

            logger.LogCritical($"Application configurations: StringValue = {appConfig.Value?.StringValue}; BoolValue = {appConfig.Value?.BoolValue}");

            /*Create a user*/
            var user = new ApplicationUser { FirstName = "Azure", LastName = "Kontext" };

            /*Now read the users from the in memory database*/
            var users = dbContext.ApplicationUsers;
            foreach (var u in users)
                logger.LogCritical($"FirstName={u.FirstName}, LastName={u.LastName}");

The above used methods are standard EF APIs and please read through Entity Framework documentation if you want to learn more.

Run and trigger the function

Start the Azure Functions application in Visual Studio and then upload a file into the specified local container to trigger the function.

The following screenshot is one sample output:



The above example utilizes in-memory database. You can connect to all Entity Framework supported databases (both on-premise or on cloud), such as SQL Server, Oracle, PostgreSQL, MySQL, etc.


Entity Framework documentation

More from Kontext
info Last modified by Raymond 3 years ago copyright This page is subject to Site terms.
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts