Azure Functions Entity Framework - Part 2

In this post we will look at using Entity Frameworks Entity models and using our DbContext to create mappings and use these mappings in our Azure function. Azure functions use Code First approaches to Entity Framework.

Source code for this demo can be found here

For Azure Functions Entity framework - Part 1 covers the basics of adding Entity Framework to our Azure Function.

Getting Started

project.json

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

Our run.csx will look something like this.

#r "System.Data"

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

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

    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);
    e.Created_DT = System.DateTime.Now;
    
    try
    {        
        using (PeopleContext context = new PeopleContext())
        {
            context.Persons.Add(e); 
            context.SaveChanges();            
        }
    }
    catch(System.Data.Entity.Infrastructure.DbUpdateException ex)
    {
        log.Info(string.Format("Failure with database update {0}.", ex.Message));        
    }      

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

public class PeopleContext : DbContext
{
    public PeopleContext()
        : base("XXXX")
    { }

  public DbSet<Person> Persons { get; set; }
}

public class Person{
    public int Id { get; set; }
    public string FirstName_VC {get;set;}
    public string LastName_VC {get;set;}
    public string Email_VC {get;set;}
    public DateTime Created_DT {get;set;}
}

So lets go through what we're doing here. We'll start on our code from the bottom up.

Entity Model

public class Person{
    public int Id { get; set; }
    public string FirstName_VC {get;set;}
    public string LastName_VC {get;set;}
    public string Email_VC {get;set;}
    public DateTime Created_DT {get;set;}
}

We have our Person Class, this the entity we're going to use. We have a table in the database called "Person"

Note: Azure functions use a code first approach to EF. So if the person table doesn't exist it gets created the first time you try to insert data.

DbContext

With Entity framework we create a Dbcontext and create the mapping for our classes to the database.

public class PeopleContext : DbContext
{
    public PeopleContext()
        : base("XXXX")
    { }

  public DbSet<Person> Persons { get; set; }
}

We create a PeopleContext and pull in the DbContext. We then set the connection string as we want.

public DbSet<Person> Persons { get; set; }

Sets up our entity we can use Persons in our code now to get the table.

Wire the function

    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);
    e.Created_DT = System.DateTime.Now;

Will take the Json Payload from the request and Deserialize it into an object of type Person for e.

We take e and open a context to our database.

    try
    {        
        using (PeopleContext context = new PeopleContext())
        {
            context.Persons.Add(e);
            context.SaveChanges();            
        }
    }
    catch(System.Data.Entity.Infrastructure.DbUpdateException ex)
    {
        log.Info(string.Format("Failure with database update {0}.", ex.Message));        
    }   

We add e to our persons entity and then save our changes.

This will result in a new record in the table.

Sample Payload.

{
 "FirstName_VC": "serversncode",
 "LastName_VC": "Entity",
 "Email_VC": "test@test.com"
}

That's it, in a single run.csx file we can build on our EF models to create a database connection. Remember functions are short lived things and "You had one job" kind of things so keeping our models simple and clear is important when it comes to functions.

I've made the sample as narrow as I could, for more on Serverless in Azure check out our series on Azure Functions


CloudStatus

We have been using cloud services to build products and web sites getting alerts has helped us stay ahead of issues that might happen. We track over 300 sources of information for Microsoft Windows Azure, Google Cloud, Amazon Web Services, MailGun, Github, bitbucket and more.

Try Cloudstatus
comments powered by Disqus