In this post we'll walk through loading Entity Framework into an Azure function, Saving data to our database. There can be alot of ceremony in setting up Entity Framework but it's straight forward to do.

In this post we will load Entity Framework and use our DbContext to send data into the database.

Entity Framework (EF) is an object-relational mapper (ORM) that enables developers to work with relational data using domain-specific objects.

Azure functions for more information check out my series of posts on Azure functions

Source code can be found here

HTTP Trigger Function

We'll start with our favourite kind of function a HTTP Trigger function. I've cleared the default template and used a simpler version for this demo

run.csx

#r "System.Data"

using System.Net;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    string name = "";
    
    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);

    name = e.firstname + " " + e.lastname;

    

    return req.CreateResponse(HttpStatusCode.OK, "Ok");
}

public class Person{
    public string firstname {get;set;}
    public string lastname {get;set;}
    public string email {get;set;}
}

Project.json

{
 "frameworks": 
 {  
  "net46":
  { 
   "dependencies":
   {
     "Newtonsoft.Json": "10.0.3"
   }
  }
 }
}

Entity Framework

The first part of bringing Entity Framework to play is to add it into our project.json file.

{
 "frameworks": 
 {  
  "net46":
  { 
   "dependencies":
   {
     "Newtonsoft.Json": "10.0.3",
     "EntityFramework": "6.1.3",
     "System.Data.Common": "4.3.0"
   }
  }
 }
}

Add the 2 nuget references for Entity Framework and System.Data.common to the dependencies.

     "EntityFramework": "6.1.3",
     "System.Data.Common": "4.3.0"

And Save. Allow the function to restore the nuget packages.

run.csx

Now in our run.csx we can start to get down to work

First up we need to pull in the namespaces we want to use.

You know what to do.

using System.Linq;
using System.Data.Entity;

Now we add our code into the run.csx

    try
    {        
        using (var context = new DbContext(XXXX))
        {
            context.Database.Connection.Open();
            
            context.Database.ExecuteSqlCommand(string.Format("INSERT INTO [dbo].[SubscriberDemo] ([FirstName_VC],[LastName_VC], [Email_VC],[Created_DT])" +  
                    "VALUES ('{0}', '{1}', '{2}',GETDATE()) ", e.firstname,e.lastname, e.email));
                    
            context.Database.Connection.Close();
        }
    }
    catch(System.Data.Entity.Infrastructure.DbUpdateException ex)
    {
        log.Info(string.Format("Failure with database update {0}.", ex.Message));        
    }  
    

Ok lets walk through this.

        using (var context = new DbContext(XXXX))
        {
            context.Database.Connection.Open();

We create our context from DbContext and pass the connection string. Then we open the connection.
Note: You can setup the connection string as you want. Through an appsettings if you want I have avoided getting into details here just so I can create clear samples.

 context.Database.ExecuteSqlCommand(string.Format("INSERT INTO [dbo].[SubscriberDemo] ([FirstName_VC],[LastName_VC], [Email_VC],[Created_DT])" +  
                    "VALUES ('{0}', '{1}', '{2}',GETDATE()) ", e.firstname,e.lastname, e.email));

Next we create a SQL command and execute it from our context.

Take our json payload and send it into the Azure function

{
 "firstname": "serversncode",
 "lastname": "Azure function",
 "email": "[email protected]"
}

That's it. We've now used Entity framework in an Azure function and loaded data into our database.

This is just part 1. In the next post we will get into the details of using Entity models.