Exploring Azure Functions HTTP trigger using EF Core

Introduction

The HTTP trigger lets you invoke a function with an HTTP request. These HTTP trigger lets you build serverless api and respond to the webhooks.

In case you haven’t read my previous article, I would recommend you to read from here

Attributes

Attribute PropertyDescription
RouteIt define the route template on which the endpoint is listening. The default value of the route is set to api/<FunctionName>.
AuthorizationLevelAzure Function protects your HTTP trigger using Authorization keys. Authorization Level comes with three flavour
– Anonymous: No key is required.
– Function: A specific function key is required. This is the default value if none is specified.
– Admin:A master key is required.
MethodsThis is used to define HTTP verbs for the functions.

Coding

Lets begin with creating a new Azure Functions project by select the trigger type as HTTP.

Add Nuget package

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
Microsoft.Azure.Functions.Extensions

Add the entity Model

public class Employee
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public double Salary { get; set; }

        public string City { get; set; }

        public string State { get; set; }
    }

Next, I’ll create a plain context for the data model to interact.

 public class EmployeeContext : DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> dbContextOptions) : base(dbContextOptions)
        {

        }

        public DbSet<Employee> Employees { get; set; }  
    }

Write Function code to inject context

To inject the EmployeeContext in our HTTP Function, we first need to register the context in configure method of the FunctionStartUp.

[assembly: FunctionsStartup(typeof(HttpTriggerVerify.Startup))]
namespace HttpTriggerVerify
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            string SqlConnection = Environment.GetEnvironmentVariable("SqlConnectionString");
            builder.Services.AddDbContext<EmployeeContext>(x => x.UseSqlServer(SqlConnection));
        }
    }
}
public  class HttpTriggerVerify
    {
        private readonly EmployeeContext employeeContext;

        public HttpTriggerVerify(EmployeeContext employeeContext)
        {
            this.employeeContext = employeeContext;
        }

        [FunctionName("HttpTriggerVerify")]
        public   IActionResult GetEmployees(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req,
            
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            var employees=employeeContext.Employees.ToList();
            return new OkObjectResult(employees);
        }

        [FunctionName("SaveEmployee")]
        public async Task<ActionResult> SaveEmployeeAsync([HttpTrigger(AuthorizationLevel.Anonymous,"post")] HttpRequest req
            ILogger log)
        {
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var data= JsonConvert.DeserializeObject<Employee>(requestBody);
            await employeeContext.Employees.AddAsync(data);
            await employeeContext.SaveChangesAsync();
            return new OkResult();
        }
    }

In this example, we are using two functions

  • GetEmployees: Get all the employees from the DB
  • SaveEmployee: Insert the employee related information to DB

Here, I using the Authorization level as Anonymous for simplicity purpose.

Executing EF Core Migration

Now, run the EF core migration by using below commands

//For Mac
dotnet ef migrations add InitialContext

For Windows
add-migrations InitialContext

After running the migration command, error is thrown suggesting unable to find project dll in the netcoreapp folder. But, you can find the project dll file inside the netcoreapp’s bin folder.

Unfortunately, for the design time tools like EF core migration expects the dll’s to be present in the root of build target. To make the EF core migration happy, we need to add post build event to copy the dll to the root of build target

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="cp "$(TargetDir)bin\$(ProjectName).dll" "$(TargetDir)$(ProjectName).dll"" />
  </Target>

Again after running the migration script, EF core is now complaining about not able to find the desired context. We can fix it by using IDesignTimeDbContextFactory<T>.

public class EmployeeContextFactory : IDesignTimeDbContextFactory<EmployeeContext>
    {
        public EmployeeContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<EmployeeContext>();
            optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable("SqlConnectionString"));

            return new EmployeeContext(optionsBuilder.Options);
        }
    }

After running the migration script, everything seems to be working perfectly! Now, update the database with the latest migration

//For Mac
dotnet ef database update

//For Windows
update-database

Now, I can see Employee table is being added to the DB.

Finally, we have managed to put all the code changes in place. Run the application and verify the GetEmployees and SaveEmployee methods are working as expected.

I hope you like the article. In case, you find the article as interesting then kindly like and share it.

2 thoughts on “Exploring Azure Functions HTTP trigger using EF Core

  1. Pingback: Exploring Azure Functions- Bindings – Articles on latest .net technology

  2. Pingback: Query and Mutation in GraphQL- Part two – Articles on latest .net technology

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s