Entity Framework Azure Functions

One of the best ways to work with the Azure Function is to use the Entity Framework with your Azure Function Code. So here, I will show you how to implement the Entity Framework with Azure Function using C# code.

Without causing a delay, Let’s start creating the Azure Function Project, where we will implement the Entity Framework Code. We will use Visual Studio 2019 to develop the Azure Function Project.

Open the Visual Studio 2019, click on the Create a New Project button to create the new Azure Function Project

In the next window, choose the Azure Function Project template and click the Next button.

azure functions entity framework

Provide the Project Name and the location where you want to save the Azure Function project on the Configure your new project window and click the Create button.

Using Entity Framework Core on Azure Functions

On the Create a new Azure Functions Application window, select the HTTP Trigger, Select the Storage Account(AzureWebJobsStorage) option as the Storage Emulator, and For the Authorization level option, select the Function option.

Azure Function With Entity Framework 1

Now, the Azure Function Project has been created successfully.

azure functions entity framework provider

Now, since we need to implement the Entity Framework Provider for our Azure Function Project, we need to add the 4 NuGet packages. To add the Nuget Package, Right-click on the Azure Function Project —> Click on the Manage NuGet Packages option.

Search for the Microsoft.Azure.Functions.Extensions and then click on the Install button to install the Microsoft.Azure.Functions.Extensions package

Entity Framework and Azure Function 1

The next step is to click the I Accept button to accept the License Agreement. Once you accept the License Agreement, then Microsoft.Azure.Functions.Extensions NuGet package will install successfully for the Azure Function Project.

In the same way, you can add the below NuGet packages. You can install the latest available versions

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Tools

Now, the next step is to create the Data Context class that needs to be inherited from the DbContext class

Below is my model class that is ArticleContext.cs. It contains the below code

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using System;
using System.Collections.Generic;
using System.Text;

namespace MyAzurefunctionEF
{
    public class ArticleContext : DbContext
    {
        public ArticleContext(DbContextOptions<ArticleContext> options)
            : base(options)
        { }

        public DbSet<Article> Articles { get; set; }
        public DbSet<PostArticle> PostArticles { get; set; }
    }
    public class Article
    {
        public int ArticleId { get; set; }

        public ICollection<PostArticle> PostArticles { get; set; }
    }

    public class PostArticle
    {
        public int PostArticleId { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }

        public int ArticleId { get; set; }
        public Article Article { get; set; }
    }
    
public class BloggingContextFactory : IDesignTimeDbContextFactory<ArticleContext>
    {
        public ArticleContext CreateDbContext(string[] args)
        {
            var oB = new DbContextOptionsBuilder<ArticleContext>();
            oB.UseSqlServer(Environment.GetEnvironmentVariable("mysqlconn"));

            return new ArticleContext(oB.Options);
        }
    }
}

Your Function1.cs file code will be like below

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Linq;
using System.Threading;

namespace MyAzurefunctionEF
{
    public class Function1
    {
        private readonly ArticleContext _context;
        public Function1(ArticleContext context)
        {
            _context = context;
        }
        [FunctionName("GetArticleDetails")]
        public IActionResult GetArticleDetails(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("GetArticleDetails function processed a request.");

            var articleArray = _context.PostArticles.OrderBy(p => p.Title).ToArray();
            return new OkObjectResult(articleArray);

           
        }
        [FunctionName("SubmitArticlePost")]
        public async Task<IActionResult> SubmitArticlePost(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "article/{articleId}/postarticle")] HttpRequest req,
            int articleId,
            CancellationToken ctoken,
            ILogger log)
        {
            log.LogInformation("SubmitArticlePost trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            PostArticle pa = JsonConvert.DeserializeObject<PostArticle>(requestBody);

            PostArticle p = new PostArticle
            {
                ArticleId = articleId,
                Body = pa.Body,
                Title = pa.Title
            };
            var ent = await _context.PostArticles.AddAsync(p, ctoken);
            await _context.SaveChangesAsync(ctoken);
            return new OkObjectResult(JsonConvert.SerializeObject(ent.Entity));
        }

        [FunctionName("SubmitArticle")]
        public async Task<IActionResult> SubmitArticle(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "article")] HttpRequest req,
            CancellationToken c,
            ILogger log)
        {
            log.LogInformation("SubmitArticle trigger function processed a request.");

            var entity = await _context.Articles.AddAsync(new Article(), c);
            await _context.SaveChangesAsync(c);
            return new OkObjectResult(JsonConvert.SerializeObject(entity.Entity));
        }
    }
}

Your Local.settings.JSON file code should look like the below

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "mysqlconn": "Server=tcp:sql1246.database.windows.net,1433;Initial Catalog=MySQLDB;Persist Security Info=False;User ID=YourUserID;Password=yourpassword;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  }
}

Your Projectname.csproj should look like below

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.8">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.8">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.1.8" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.36" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

You may also like following the articles below

Conclusion

In this article, we discussed how to use Entity Framework in Azure Functions. Thanks for reading this article !!!