What is it?

Entity Framework is a relational mapper that allows you to create your database schema by starting with your models and telling the ORM how each component should be created as well as how they’re related to each other. It is primarily used as a facilitator of Domain-Driven Design, but more on that later. Maybe.

Why use Code First?

Based on my experience, it allows for

  • More control over your database and models: You can practically create your database in a very few lines
  • Not having to worry about creating your database. You just have to know where the server is and which rights you should give your solution. In the end it all comes down to ease of deployment
  • Not having to worry about your SQL Statements. You will mostly be using LINQ, which (I  hope) you’re already using anyway. Saving your changes is as easy as calling SaveChanges();

Why it’s not for you

  • Starting out can be a bit of a pain, as there’s a steep learning curve.  Like really, especially when creating your database. It throws out error messages that doesn’t even match what the issue is. You just have to overcome that initial struggle, then it’s smooth sailing.
  • Although it’s a good thing to not having to worry about SQL Statements, it can also work against you depending on your habits as a programmer but if you have proper unit tests, you should be fine.

Getting Started

We’re using a Patient Management System for a sample. All it does is take the name and time on a table with a constraint and display the same data just to prove that we can insert and read. Grab my sample code here: https://github.com/johnconraddomingo/EfCodeFirst.PatientManagement

This sample uses Entity Framework  6.1.3

Basic Components

Entities: The coded representation of database tables

We’re using Patient and Appointment.

public class Patient
  public Patient()
       PatientAppointments = new List<Appointment>();
   public int PatientId {get;set; }
   public string PatientName { get;set; } 
   public virtual ICollection<Appointment> PatientAppointments{ get;set; }

Each patient can potentially contain multiple Appointments. And this relationship is defined by the ICollection in the parent. Notice the PatientAppointments in the Patient class.

public class Appointment
    public int AppointmentId { get; set; }
    public DateTime AppointmentDateTime { get; set; } 

You’ll notice that the table looks like a regular class: And that’s the beauty of it all. We isolate the database part and just focus on our object. Now here’s where we

Entity Mapping

Now here’s where we tell EF the attributes of the fields such as

  • The Primary Keys
  • If they’re mandatory or optional fields
  • Max Length
public class PatientMap : EntityTypeConfiguration<Patient>
    public PatientMap()
        // Key 
        HasKey(k => k.PatientId);
        // Properties
 Property(p => p.PatientId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
 Property(p => p.PatientName).IsRequired().HasMaxLength(50);
        // To Table
    • The table name that they correspond to
public class AppointmentMap : EntityTypeConfiguration<Appointment>
        public AppointmentMap()
            // Key
            HasKey(k => k.AppointmentId);
            // Properties
 Property(p => p.AppointmentId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
 Property(p => p.AppointmentDateTime).IsRequired();
            // To Table

The DB Context

This is our representation of the Database. Here we define

    • The Database name


  • Which tables we want to include in our database



  • The mapping classes that we defined earlier



  • Other configs



public class PatientManagementDatabase : DbContext
    public PatientManagementDatabase() : base("PatientManagementContext")
        Configuration.LazyLoadingEnabled = true;
        Configuration.ProxyCreationEnabled = false;

public DbSet<Patient> Patient { get; set; }
public DbSet<Appointment> Appointment { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
  modelBuilder.Configurations.Add(new AppointmentMap());
  modelBuilder.Configurations.Add(new PatientMap());

Create Datasource

This is where we put everything together: We tell EF how to create the database. You decide where to call this method: Beginning of your application? App_Start?  Either way, it should be safe to call it anytime because within the initialiser you tell the framework when to create.

private static void CreateDatasource()
    Database.SetInitializer(new CreateDatabaseIfNotExists<PatientManagementDatabase>());var context = new PatientManagementDatabase();

That’s it! Now, we just play around with it by LINQ. This is a very simple example that you can build your more complex applications from.

You can download the sample from https://github.com/johnconraddomingo/EfCodeFirst.PatientManagement