Tuesday, April 3, 2012

EntityFramework 4 - Code First v Model First (pros and cons)

I have worked on MVC 3 projects using both Code First and Model First. From my personal experience here were the pros and cons I could think of:

Code First Pros | Model First Cons

  • For Model First approach, DB generated names are not friendly especially if the DBA/Organization follows rules such as OAT0012 for table(entity) names and FSN_XXX for column names. Although, you can manually edit this, it will all go away during a refresh/update. But with Code First Approach you can have User(Developer)-friendly names like Person or Account as table(entity) names and AccountID as field names and not worry about that changing.

  • Create relationships as you need them, like the way you want them to behave (bi-directional/uni-directional)

  • Generated code is not always easy to understand, especially when the database is not 3N-normalized. With this, you can add your own relationships to maintain relationships. Now I have also seen Id field mapping to another entity as well as that entity as an object within the same entity. Duh!

  • When working on a team Model First can sometimes be a pain. This is true in initial development when changes are frequent to the database. You could say that this is true for Code First too. To some degree, Yes. But if the DBA's model does not suit your Controller's need and you need to hack into one or two entities, you would have to consider keeping local changes (branching out your repo) and updating the team's changes and applying your changes again.


Code First Cons | Model First Pros

  • You are up and running as soon as the database is ready and you can immediately start working on your service methods.

  • If you have a complex database the relationships that are automatically created for you in a matter of seconds. This is probably why people choose to go with this when they do it.

  • You do not need to read an entire book to get started with EF if you choose this option. Probably another reason to go with this.


Overall, the deciding factors, if I was choosing would be, is there going to be a lot of changes to the database? If so, I would stick to CodeFirst. It also suits Agile way of working. Creating only what you need to get the unit of work done and making changes as you go along. Also, if the database is not normalized, generated code would not be very helpful. But with a complex database and that which is almost ready, I would, for sure, prefer Model First.