Category Archives: Entity Framework

Entity Framework – The Basics

Entity Framework makes creating and accessing databases easier and removes the need to write lots of data access code.

Getting Started

Add the NuGet packege listed below to your project – searching the NuGet package manager for “Entity Framework” should bring it up.

Creating a Model

Firstly we need a create a model that will represent our data, this can just be a simple C# class with a couple of properties. Below is a simple customer model.

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Creating a Context

Now we need to create a context which will handle the communication with the database.

public class CustomerContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

Putting It All Together

Finally we just need to add some code that will save a customer instance into our database.

using( CustomerContext ctx = new CustomerContext() )
{
    Customer customer = new Customer() { Name = "Bob Smith" };
    ctx.Customers.Add( customer );
    ctx.SaveChanges();
}

Finally

You may wonder why the code above works as we didn’t create a database, the beauty of Entity Framework is that it does all of this for us. If you check Sql Server Management Studio you should notice that a database has been created along with a table for our customers.