All Articles

Entity Framework: Database-First vs Code-First

When working with Entity Framework (EF) Code-First, we define our entity model with classes and mappings in code, and the database is generated from the model. When we change the model, we can evolve the database using Migrations.

 

In the past, I've used more the Database- First approach (rather than the Code First). In the Database-First approach we start to model the database artifacts (tables, views, primary keys, foreign keys, etc.), and then we have the entity model generated from the database.

 

In the earlier versions, EF didn't support the Code-First approach. Today, EF already supports this approach, and it has been improved in every new version. I decided to try this approach in my current project, and I would like to enumerate some advantages:

  • all my application "runnable" artifacts are written in C#
  • no need to have a different database project to accommodate the data artifacts
  • faster development workflow
  • makes me think in advance about "the scripts" that will run to upgrade/downgrade my database to accomodate model changes. (every migration has an up and down path, where you can run sql migration statements)

 

However, I also can enumerate some disadvantages

  • if your model is changing a lot, and you are working in a team with more than 3 elements, I believe that the team will struggle easily with migrations (the migrations folder starts to grow and it get's out of control)
  • Some annotation attributes are missing, such as the Index attribute for example. Currently, with EF 6, I cannot decorate my entity properties with an Index annotation. To create an index over a given property, I have to use the fluent API. I tend to prefer the attribute annotations approach.
  • some lack of control how the database artifacts will be generated

 

I believe that those more conventional/traditional developers will continue to use the well known Database-First approach. In my case, since I know both approaches, I will support my choice based on context/environment: team and project dimension, type of customer, etc. But now I can say that I'm really confident and confortable with the Code-First approach, and certainly I will use it regularly.

Published Nov 26, 2013

Cloud Solutions and Software Engineer. Married and father of two sons. Obsessed to be a continuous learner.