ASP.NET WebAPI - Entity Framework Code First
Introduction
This article walks you through configuration of Entity framework 6.1 on a WebAPi project.
For that we will create a model "Contacts", where we can save data from contact persons.
STEP 1 - Create ASP.NET WebAPI 2 Application
I will be using Visual Studio 2013 as my development environment. Our first step will be to create an ASP.NET Web Application project based on the Web API template:
- Open Visual Studio 2013 and create a new project of type ASP.NET Web Application.
- On this project I create a solution called WebAPI.
http://code.msdn.microsoft.com/site/view/file/125769/1/1.png
- Press OK, and a new screen will appear, with several options of template to use on our project.
- Select the option WebAPI.
http://code.msdn.microsoft.com/site/view/file/125770/1/2.png
- The solution will be created.
STEP 2 - Install Nuget
Now in order to use Entity Framework we need to install a Nuget package.
So on the Visual Studio 2013, select the follow menu option:
- Tools-> Library Package manager -> Manage NuGet Packages for Solution
- Search for Entity Framework and select the option Install.
http://code.msdn.microsoft.com/site/view/file/125771/1/3.png
This option, will install automatically the Nuget Package.
STEP 3 - Create Data Model
After we have our web application created, we need to create our data model.
For that, we can create a new class Contact with the follow code:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace SampleEF6.Models
{
public class Contact
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
}
STEP 4 - Configure Data Context
The context must receive on the constructor the name of connection string, so we name it "DefaultConnection", and we will show on the next steps how to configure it.
On the context, we need to define the DBSet, that represent each model created on the below step. On this example we only have one model so we will define it.
C#
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace SampleEF6.Models
{
public class EFContext : DbContext
{
public EFContext()
: base("name=DefaultConnection")
{
base.Configuration.ProxyCreationEnabled = false;
}
public DbSet<Contact> Contacts { get; set; }
}
}
Set some initial data. For that we can use the Seed method. This method allows us to insert initial data to every data model created on context.
C#
namespace SampleEF6.Migrations
{
using SampleEF6.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<SampleEF6.Models.EFContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "SampleEF6.Models.EFContext";
}
protected override void Seed(SampleEF6.Models.EFContext context)
{
context.Contacts.AddOrUpdate(
p => p.Name,
new Contact { Name = "João Sousa", Address= "Street x", City = "Porto", Country = "Portugal" },
new Contact { Name = "Steve Jon", Address = "Street y", City = "Porto", Country = "Portugal" },
new Contact { Name = "Peter", Address = "Street z", City = "Porto", Country = "Portugal" }
);
}
}
}
STEP 5 - Create Contact controller
Contact controller CRUD methods:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SampleEF6.Models;
namespace SampleEF6.Controllers
{
public class ContactController : ApiController
{
private EFContext db = new EFContext();
// GET api/<controller>
[HttpGet]
public IEnumerable<Contact> Get()
{
return db.Contacts.AsEnumerable();
}
// GET api/<controller>/5
public Contact Get(int id)
{
Contact Contact = db.Contacts.Find(id);
if (Contact == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return Contact;
}
// POST api/<controller>
public HttpResponseMessage Post(Contact Contact)
{
if (ModelState.IsValid)
{
db.Contacts.Add(Contact);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Contact);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Contact.Id }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
// PUT api/<controller>/5
public HttpResponseMessage Put(int id, Contact Contact)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
if (id != Contact.Id)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
db.Entry(Contact).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
// DELETE api/<controller>/5
public HttpResponseMessage Delete(int id)
{
Contact Contact = db.Contacts.Find(id);
if (Contact == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Contacts.Remove(Contact);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK, Contact);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\sampleDB.mdf;Initial Catalog=sampleDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
To create the database we need to run some command line instructions on the package manager console.
Enter the following instruction:
http://code.msdn.microsoft.com/site/view/file/125774/1/6.png
The database will be created with the data model Contacts as we see on the next image.
http://code.msdn.microsoft.com/site/view/file/125772/1/4.png
STEP 6 - Test WebApi
We can now call api/contact to receive every contact on database.
http://code.msdn.microsoft.com/site/view/file/125773/1/5.png
Resources
Some good resources about Windows Azure could be found here:
- My personal blog: http://joaoeduardosousa.wordpress.com/
- Download Code: http://code.msdn.microsoft.com/ASPNET-WebAPI-Entity-2f8797a1/view/Reviews