The HTTP trigger lets you invoke a function with an HTTP request. These HTTP triggers let you build a serverless API and respond to the webhooks.
Coding
Let's begin by 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 am using the Authorization level as Anonymous for simplicity purposes.
Executing EF Core Migration
Now, run the EF core migration by using the below commands.
-
- dotnet ef migrations add InitialContext
- For Windows
- add-migrations InitialContext
After running the migration command, an error is thrown suggesting it's unable to find the project dll in the netcoreapp folder. But, you can find the project dll file inside the netcoreapp’s bin folder.
Unfortunately, the design time tools like EF core migration expect 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 being 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
-
- dotnet ef database update
-
- 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. If you found this article interesting then kindly like and share it.