Raymond Raymond

Use Entity Framework in .NET 5 Azure Functions

event 2021-08-24 visibility 3,285 comment 0 insights toc
more_vert
insights Stats
Use Entity Framework in .NET 5 Azure Functions

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. 

Prerequisites

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:

  <ItemGroup>
    <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" />
  </ItemGroup>

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
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        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)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<ApplicationUser>()
                .ToTable("Users");
        }
    }
}

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();
                })
                .ConfigureFunctionsWorkerDefaults()
                .ConfigureServices(services =>
                {
                    services.AddOptions<AppConfig>().Configure<IConfiguration>((settings, configuration) => configuration.GetSection("AppConfig").Bind(settings));
                    services.AddDbContext<ApplicationDbContext>(options =>
                    {
                        options.UseInMemoryDatabase("AzureFunctionExample");
                    });
                })
                .Build();

            host.Run();
        }
    }
}

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;
        }

        [Function("Function1")]
        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" };
            dbContext.Add(user);
            dbContext.SaveChanges();

            /*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:

2021082953641-image.png

Summary

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.

References

Entity Framework documentation

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts