Menu

Entity Framework – When to use what

20th October 2015 - c#, developer, Development

In Entity Framework there are three ways of utilising the ORM, one enables you to get straight into coding (code-first), one enables you to rip a database into a new model (database-first) and the final one enables you to create a model independent of the database or your final code (model-first).

But, when should I use each of these methods?

Each method has its pro’s and con’s, and personally, I don’t really use code-first that often as it lends itself to a build where everything has been fully architected beforehand, and all you’re doing is building to spec. Something I rarely encounter, as the initial green field development is often a very agile process, especially if you’re utilising a TDD/BDD development cycle.

So what scenario would you legitimately use Code-First?

Say you have a very small micro-service to build, such as an auditing service, and you already know the database fields, and possibly the service will only know its connection at runtime. Code-First is an ideal solution, as it enables you to quickly knock out the code, leaving the spinning up and implementation of the database to the EF settings in config. The main drawback I find of Code-First is that if you’re database schema is not set in stone, a rebuild of your EF model will necessitate a destruction of the database. You can create a custom upgrade path, but this is rarely done. So, if you have a unchanging model, for a small data footprint, code-first is great.

Code-First is also great for proof-of-concept builds that may be knocked out in a day to show a particular prospect of development.

Database-First is obviously good for where your development is bound to a database schema which already exists and is quite complex. You can just use the EF designer in Visual studio to generate the model and get up and running very quickly. A database schema change will mean that the EF model will need to be recreated, but its generally no big deal as the database will be keeping its data integrity due to it being developed in its own development domain by DBAs or other colleagues.

Model-First would generally be used to map out a logical structure of the data which bridges both the system model and the database model. Say you wish to use a different paradigm of data design in the database to your model (flat-file DB with a relational ORM). It could also be the case that you are tasked with a data-design task where you need to develop a schema that satisfies the requirements of the database team and the architect, utilising a colourful database like Oracle or MySQL to fit.

I hope this helps your decide the approach to use when implementing Entity Framework in your work.

Take care