Code First Entity Framework - Data Annotations

1. Entity Framework allows you to code your POCO classes first, then use a Context object to manage the database persistance.

But because databases have peculiarities, such as keys and identity columns, some control over how EF implements your data object in the database may be required. EF allows you to do this in a couple of ways: a Fluent API lets you do it in code, or the simpler way using Data Annotations, which we'll use here.
2. Say you are modelling a school, and you need a Pupil object. You design the POCO object in code with 4 properties, id, name, DOB, and primary school attended:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestEF.Entity
{
    public class Pupil
    {
        public int PupilId { get; set; }

        public string Name { get; set; }

        public DateTime DateOfBirth { get; set; }

        public string PrimarySchool { get; set; }
    }
}
Now we know databases, and we know a few things about how this needs to be implemented in a database - we could go create a new table called Pupils, with 4 columns, the PupilId column will be the Primary Key and will be a generated identity column. Name and the DOB fields will have to be not nullable, but PrimarySchool can be optional. We would decide to implement max lengths on the nvarchar fields for Name (say 100 chars) and PrimarySchool (say 200 chars). But instead of creating it by hand, we can Annotate the fields in the class to do all these things and EF will create it for us.

Add a using line for the DataAnnotations namespace:
using System.ComponentModel.DataAnnotations;
3. Firstly we can deal with the Primary Key. There is a [Key] attribute we can put on the field we want as the key.
    public class Pupil
    {
        [Key]
        public int PupilId { get; set; }

        public string Name { get; set; }

        public DateTime DateOfBirth { get; set; }

        public string PrimarySchool { get; set; }
    }
When the database is created from this data object, the column created for PupilId will be set as the Primary Key.
4. Secondly, we can set the non-nullable fields by using the [Required] attribute on the three columns we want non-nullable.
    public class Pupil
    {
        [Key]
        [Required]
        public int PupilId { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public DateTime DateOfBirth { get; set; }

        public string PrimarySchool { get; set; }
    }
5. Now we can set the max char lengths on the two string fields suing the [StringLength] attribute.
    public class Pupil
    {
        [Key]
        [Required]
        public int PupilId { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        [Required]
        public DateTime DateOfBirth { get; set; }

        [StringLength(200)]
        public string PrimarySchool { get; set; }
    }
6. Finally, we can set the primary key as an identity column using the DatabaseGenerated attribute.
    public class Pupil
    {
        [Key]
        [Required]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int PupilId { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        [Required]
        public DateTime DateOfBirth { get; set; }

        [StringLength(200)]
        public string PrimarySchool { get; set; }
    }
Note this hasn't changed our class in any way, it's still just a POCO class, all the annotations have done is provide Entity Framework with enough information to create the database when it comes to do it.
7. To bind this model to an actual database table, we need to create a new class to hold the DbContext for our School application and make it inherit from DbContext.
using System.Data;
using System.Data.Entity;
using System.Data.EntityModel;

namespace TestEF.Contexts
{
    public class SchoolContext : DbContext
    {
        public DbSet<TestEF.Entity.Pupil> Pupils { get; set; }
    }
}
This class creates an inherited instance of DbContext, which we call here SchoolContext, and defines a DbSet as a member. This generic object takes a type contructor, and by passing our Pupil object, we are basically telling Entity Framework to bind the object to a database table.
8. Because Entity Framework can bind to any data store, or to existing database tables for instance, we don't want the default behaviour to be that it creates the table if it doesn't exist. EF defaults to creating the tables to support the models if you are using SQLEXPRESS, but for production databases it isn't so bold, and you have to make it do it.

In Golbal.asax, add the appropriate using line
    using System.Data.Entity;
and the following line to the Application_Start() event:
    Database.SetInitializer<TestEF.Contexts.SchoolContext>(new DropCreateDatabaseAlways<TestEF.Contexts.SchoolContext>());
This tells Entity Framework, that for the SchoolContext object, it must always Drop and Recreate the tables every time. This may be a bit extreme, since dropping the tables will remove all data each time the application is restarted. The other options are more usual: DropCreateDatabaseIfModelChanges and CreateDatabaseIfNotExists. It's usual for developers to use these options while they are developing the system, to propagate their DB changes to the database, but then to remove them once in production and the databases are established.

The database is now ready to be created automagically! Almost....
9. All this holding ourselves apart from the database layer and letting EF do the dirty work means we've not thought about how EF knows which database to connect to - we have to supply it a database connection string. As usual, there are two ways to do it, one convention, one configuration.

By default, EF looks in the ConnectionStrings section of web.config for a ConnectionString named after the DbContext you've used in your code. Since we created a SchoolContext, all we have to do is add a named ConnectionString in web.config and the rest is magic.
    <add name="SchoolContext"
         connectionString="Persist Security Info=False;Initial Catalog=MySchoolDB;Server=MYSERVER/Instance;Connect Timeout=30"
         providerName="System.Data.SqlClient"  />
If we need to get the ConnectionString from somewhere else, or we can't fix the name of it in web.config to be the same as the Context then we need to pass it in code. We do this by invoking the constructor of DbContext which accepts a connection string or the name of a ConnectionString in web.config (we didn't have a constructor before, so add one):
    public class SchoolContext : DbContext
    {
        // either of these two constructors is fine - just use the one that's most useful 
        public SchoolContext() : base("OtherNamedConnectionString") { }
        public SchoolContext() : base("Persist Security Info=False;Initial Catalog=MySchoolDB;Server=MYSERVER/Instance;Connect Timeout=30") { }

        public DbSet<TestEF.Entity.Pupil> Pupils { get; set; }
    }
This means the connection string can come from some other configuration utility in slotted in here, or it can be another named ConnectionString in web.config
10. Now we run our application, and go look in the named database to see our lovely tables. What? Theyre not there?

Well, assuming you've had no compile errors from typos, and assuming your connection string is good and you have permissions, it's likely you haven't actually used your new entities yet in your code. EF is thrifty when it comes to it, it only creates them as required. So somewhere in your code (in your aspx code behind or your MVC controller) create an instance of your class and Context and commit it:
    using (TestEF.Contexts.SchoolContext TheSchool = new TestEF.Contexts.SchoolContext())
    {
        Entity.Pupil p = new Entity.Pupil();
        p.Name = "John Curran";
        p.DateOfBirth = DateTime.Parse("25/01/1969");
        p.PrimarySchool = "St Denis";

        TheSchool.Pupils.Add(p);
        TheSchool.SaveChanges();
    }
Now after you run this, you should be able to see that it's created a Pupils table (note the pluralisation of your entity name) with the correct columns, keys, etc. And with any luck, you'll have one row in it, with your new Pupil.
And that's the basics of Entity Framework code-first with Data Annotations.